以Leetcode3. 无重复字符的最长子串为例
Java版
//package **;
import java.util.HashMap;
import java.util.Map;
class Solution_lengthOfLongestSubstring {
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> window = new HashMap<>();
int left = 0, right = 0;
int res = 0;
while (right < s.length()) {
char c = s.charAt(right);
right++;
window.put(c, window.getOrDefault(c, 0) + 1);
while (window.get(c) > 1) {
char d = s.charAt(left);
left++;
window.put(d, window.getOrDefault(d,0) - 1);
}
res = Math.max(res, right - left);
}
return res;
}
public static void main(String[] args) {
Solution_lengthOfLongestSubstring solution_lengthOfLongestSubstring = new Solution_lengthOfLongestSubstring();
int s = solution_lengthOfLongestSubstring.lengthOfLongestSubstring("pwwkew");
System.out.println(s);
}
}
C++版
#include<iostream>
#include<cstring>
#include<string>
#include<tr1/unordered_map>//注意这里
using namespace std;
using namespace std::tr1;//还有这里
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char, int> window;
int left = 0, right = 0;
int res = 0; // 记录结果
while (right < s.size()) {
char c = s[right];
right++;
// 进行窗口内数据的一系列更新
window[c]++;
// 判断左侧窗口是否要收缩
printf("window: [%d, %d)\n", left, right);
// printf("window: %c\n", window[c]);
cout<<"c:"<<c<<" "<<"window: "<< window[c]<<endl;
while (window[c] > 1) {
char d = s[left];
cout<<"D:"<<d<<endl;
left++;
cout << "left:" <<left<<endl;
// 进行窗口内数据的一系列更新
window[d]--;
cout << "window[d]:" <<window[d]<<endl;
cout << "window[c]:" <<window[c]<<endl;
}
// 在这里更新答案
res = max(res, right - left);
}
return res;
}
};
int main()
{
Solution solution;
string st = "pwwkew" ;
int ans = solution.lengthOfLongestSubstring(st);
cout <<"ans:"<< ans;
}