LeetCode No.3
Given a string, find the length of the longest substring without
repeating characters. For example, the longest substring without
repeating letters for "abcabcbb" is "abc", which the length is 3. For
"bbbbb" the longest substring is "b", with the length of 1.
思路
本题比较简单,从左往右扫描字符串,记录当前重复字串的起始位置为start,当遇到重复字符时,将start更新为重复字符的index加一,比较当前不重复字符串长度与max值,更新max值。
寻找重复字符的方式有两种,一种是用一个map记录每个字符上次出现的位置(可用hashmap或int[256]), 或者仅记录字符是否出现在start后,逐一更新start,直到当前字符不再重复。
Use map:
public class Solution {
public int lengthOfLongestSubstring(String s) {
HashMap<Character, Integer> map = new HashMap<Character,Integer>();
int maxLen = 0;
int start = 0;
for (int i = 0; i< s.length(); i++) {
if (!map.containsKey(s.charAt(i)) || map.get(s.charAt(i)) < start) {
map.put(s.charAt(i),i);
}
else {
maxLen = Math.max(maxLen,i - start);
start = map.get(s.charAt(i)) + 1;
map.put(s.charAt(i),i);
}
}
maxLen = Math.max(maxLen, s.length() - start);
return maxLen;
}
}
update start one by one
public class Solution {
public int lengthOfLongestSubstring(String s) {
boolean[] visited = new boolean[256];
int start = 0, last = 0, max = 0, length = s.length();
while(last < length) {
if(!visited[s.charAt(last)]) {
visited[s.charAt(last)] = true;
max = Math.max(max, last++ - start + 1);
} else {
while(visited[s.charAt(last)])
visited[s.charAt(start++)] = false;
visited[s.charAt(last++)] = true;
}
}
return max;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。