
leetcode的题解:
https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/solution/wu-zhong-fu-zi-fu-de-zui-chang-zi-chuan-by-leetcod/

java版:
public class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length(), ans = 0;
Map<Character, Integer> map = new HashMap<>(); // current index of character
// try to extend the range [i, j]
for (int j = 0, i = 0; j < n; j++) {
if (map.containsKey(s.charAt(j))) {
i = Math.max(map.get(s.charAt(j)), i);
}
ans = Math.max(ans, j - i + 1);
map.put(s.charAt(j), j + 1); //注:重复key会覆盖value值
//System.out.println(map);
}
return ans;
}
}
map.put(s.charAt(j), j + 1);
上面这里存的是j+1而不是j,方便i更新值
i = Math.max(map.get(s.charAt(j)), i); //取大的防止i左移
可以改成这样:

改成C++:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
map<char,int> mymap;
int ans = 0;
for(int i = 0, j = 0; j < s.size(); j++)
{
if(mymap.count(s[j]) == 1)
{
i = max(mymap[s[j]], i);
}
ans = max(ans, j - i + 1);
mymap[s[j]] = j + 1;
}
return ans;
}
};
class Solution {
public:
int lengthOfLongestSubstring(string s) {
map<char,int> mymap;
int ans = 0;
for(int i = 0, j = 0; j < s.size(); j++)
{
i = max(mymap[s[j]], i); //如果mymap里没s[j]这个key,mymap[s[j]] = 0
ans = max(ans, j - i + 1);
mymap[s[j]] = j + 1;
}
return ans;
}
};


class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int>mymap(256,-1);
int left = -1;
int res = 0;
int len = s.size();
for(int i = 0; i < len; i++)
{
left = max(mymap[s[i]], left);
mymap[s[i]] = i;
res = max(res, i - left);
}
return res;
}
};
参考:
leetcode
https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/solution/wu-zhong-fu-zi-fu-de-zui-chang-zi-chuan-by-leetcod/
本文提供了一种解决LeetCode上最长无重复字符子串问题的有效算法,通过使用滑动窗口和哈希表的方法,实现了O(n)的时间复杂度,适用于Java和C++编程语言。
869

被折叠的 条评论
为什么被折叠?



