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;
}
};
参考:
leetcodehttps://leetcode-cn.com/problems/longest-substring-without-repeating-characters/solution/wu-zhong-fu-zi-fu-de-zui-chang-zi-chuan-by-leetcod/
来源:CSDN
作者:曾庆发
链接:https://blog.csdn.net/qq_40691051/article/details/103645390