Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
难度: Medium
题意是求最长无重复子串, 给出一个字符串, 从所有子串中, 找出最长, 且没有重复字母的子串的长度.
我的解法是: (以abcbcdabb为例)
使用一个set, 记录当前子串遇到的所有字符.
用一个游标, 从头开始读取字符, 加入到set中.(a, ab, abc)
如果碰到了重复字符(i=3, 遇到了b, 重复), 则从当前子串的头部的字符开始, 将该字符从set中移除, 直到移除了当前这个重复字符为止. (abc, bc, c, cb)
期间记录不重复的最大长度.
遍历完整个字符串后, 输出最大长度.
由于使用了HashSet, 每个元素访问不超过两次(添加与移除), 所以算法时间复杂度为O(n).
public class Solution {
public int lengthOfLongestSubstring(String s) {
// a set to record chars for current substring
Set<Character> cset = new HashSet<Character>();
// length of longest non-repeat substring
int lgst = 0;
// length of current substring
int curLen = 0;
for (int i = 0; i < s.length(); i++) {
Character c = s.charAt(i);
curLen++;
// if encounters a duplicate character
if (cset.contains(c)) {
// record non-repeat length
lgst = (curLen - 1) > lgst ? (curLen - 1) : lgst;
// reduce character from the head of current substring,
// until current repeat letter is removed
for (int j = i - cset.size(); j < i; j++) {
curLen--;
cset.remove(s.charAt(j));
if (s.charAt(j) == c) {
break;
}
}
}
cset.add(c);
}
lgst = curLen > lgst ? curLen : lgst;
return lgst;
}
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.lengthOfLongestSubstring("bbbbbb"));
System.out.println(s.lengthOfLongestSubstring("abcabcbb"));
System.out.println(s.lengthOfLongestSubstring("abcbcdabb"));
System.out.println(s.lengthOfLongestSubstring("aab"));
System.out.println(s.lengthOfLongestSubstring("dvdf"));
System.out.println(s.lengthOfLongestSubstring("advdf"));
}
}
main方法执行的测试结果为:
1
3
4
2
3
3
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。