3. 无重复字符的最长子串
我的解法
- 滑动窗口(操作字符) 时间O(n)
注意点
-
遇到重复字符时,将cur和res比较长度
-
像ertezdf这种情况 遍历到第二个e时,中间的rt要被保留
-
当遍历完毕,更新res
代码
class Solution {
public int lengthOfLongestSubstring(String s) {
StringBuilder cur = new StringBuilder();
String res = "";
int now = 0;
if(s == null || s.equals("")){
return 0;
}
while(now != s.length()){
if(!cur.toString().contains(""+s.charAt(now))){
cur.append(s.charAt(now));
}else {
if(cur.length() > res.length()){
res = cur.toString();
}
String temp = cur.substring(cur.indexOf(""+s.charAt(now)) + 1,cur.length());
cur = new StringBuilder(temp);
cur.append(s.charAt(now));
if(cur.length() > res.length()) {
res = cur.toString();
}
}
if(now == s.length() - 1 && res.length() < cur.length()) res = cur.toString();
now++;
}
return res.length();
}
}
效率
优秀解法
- 仅记录数值,不记录或操作字符串
代码
class Solution {
public int lengthOfLongestSubstring(String s) {
if (s.length()==0) return 0;
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
int max = 0;
int left = 0;
for(int i = 0; i < s.length(); i ++){
if(map.containsKey(s.charAt(i))){
left = Math.max(left,map.get(s.charAt(i)) + 1);
}
map.put(s.charAt(i),i);
max = Math.max(max,i-left+1);
}
return max;
}
}