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.
Solution: (reference:http://leetcode.com/2011/05/longest-substring-without-repeating-characters.html)
Running time: O(n), worst case---start and end both move n steps, o(2n).
use two indices to find the substring, the length can be (end-start),
use boolean[] to mark the character whether is unique,
update the maxlen when we find a repeated character,
don't forget to update the maxlen after the while loop.
java中数组使用new 关键字分配空间后会赋默认值,默认值的值要看数组的类型。boolean[] 默认值为false.
public class Solution {
public int lengthOfLongestSubstring(String s) {
// Start typing your Java solution below
// DO NOT write main() function
boolean[] visited = new boolean[256];
int len = s.length();
int start = 0;
int end = 0;
int maxlen = 0;
while(end < len){
if(!visited[s.charAt(end)]){
//don't use s[end], because s is string , not char[]
visited[s.charAt(end)] = true;
end++;
}else{
maxlen = Math.max(maxlen, end-start);
while(s.charAt(start) != s.charAt(end)){
//don't forget this step, which is used to find new start
visited[s.charAt(start)] = false;
start++;
}
start++;
end++;
}
}
maxlen = Math.max(maxlen, len-start);
//if there is no repeated characters in an entire string
return maxlen;
}
}
2015-03-14更新:
Python Solution:
Running Time: O(n).
class Solution:
# @return an integersssss
def lengthOfLongestSubstring(self, s):
subStr = ''
start = 0
maxLen = 0
for end in xrange(len(s)):
if s[end] not in subStr:
subStr += s[end]
else:
maxLen = max(maxLen, len(subStr))
while s[start] != s[end]:
start += 1
start += 1
subStr = s[start:end+1]
return max(maxLen, len(subStr))