LeetCode 003 Longest Substring Without Repeating Characters O(n)做法
2018-02-16 14:27
399 查看
Given a string, find the length of the longest substring without repeating characters.Examples:Given
用HashMap加快查询速度。HashMap.containsKey复杂度O(1),HashMap.containsValue复杂度O(n)。class Solution {
public int lengthOfLongestSubstring(String s) {
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int max = 0;
for(int i = 0, j = 0; i < s.length(); i++) {
if(map.containsKey(s.charAt(i))) {
// 这里取max是因为map中的元素加入之后一直存在
// map.get能获得最后一次出现的位置
j = Math.max(j, map.get(s.charAt(i)) + 1);
}
map.put(s.charAt(i), i);
max = Math.max(max, i - j + 1);
}
return max;
}
}
"abcabcbb", the answer is
"abc", which the length is 3.Given
"bbbbb", the answer is
"b", with the length of 1.Given
"pwwkew", the answer is
"wke", with the length of 3. Note that the answer must be a substring,
"pwke"is a subsequenceand not a substring.
用HashMap加快查询速度。HashMap.containsKey复杂度O(1),HashMap.containsValue复杂度O(n)。class Solution {
public int lengthOfLongestSubstring(String s) {
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int max = 0;
for(int i = 0, j = 0; i < s.length(); i++) {
if(map.containsKey(s.charAt(i))) {
// 这里取max是因为map中的元素加入之后一直存在
// map.get能获得最后一次出现的位置
j = Math.max(j, map.get(s.charAt(i)) + 1);
}
map.put(s.charAt(i), i);
max = Math.max(max, i - j + 1);
}
return max;
}
}
相关文章推荐
- [LeetCode 003] Longest Substring Without Repeating Characters
- [Leetcode题解]003 Longest Substring Without Repeating Characters
- 003_LeetCode_3 Longest Substring Without Repeating Characters 题解
- LeetCode 003: Longest Substring Without Repeating Characters
- LeetCode003__Longest Substring Without Repeating Characters
- 【leetcode】003 Longest Substring Without Repeating Characters
- 003 Longest Substring Without Repeating Characters [Leetcode]
- 2017-09-07 LeetCode_003 Longest Substring Without Repeating Characters
- LeetCode 003 Longest Substring Without Repeating Characters
- LeetCode-003 Longest Substring Without Repeating Characters
- leetcode 003 Longest Substring Without Repeating Characters(java)
- LeetCode_003 Longest Substring Without Repeating Characters(greedy)
- LeetCode 003-Longest Substring Without Repeating Characters
- leetcode解题方案--003--LongestSubstringWithoutRepeatingCharacters
- Leetcode003 Longest Substring Without Repeating Characters
- leetcode-java.T003_LongestSubstringWithoutRepeatingCharacters 给定一个字符串,找字符中的最大非重复子串
- [LeetCode]-003-Longest Substring Without Repeating Characters
- LeetCode 003 Longest Substring Without Repeating Characters
- leetcode_c++:哈希:Longest Substring Without Repeating Characters(003)
- 【LeetCode-面试算法经典-Java实现】【003-Longest Substring Without Repeating Characters(最长非重复子字符串)】