题目
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: 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.
解析
题目含义很简单,即求出没有字符重复的子字符串的长度。例如bbbbb很明显就是个由完全重复字符组成的字符串,所以它的答案长度为1。
解法1 : 遍历字符串构成无重复字符字符串
最简单的方法就是通过遍历字符串的每一个字符,循环的构造子字符串,遇到重复字符便停止,然后得出最长长度的那个字符串。
public static int lengthOfLongestSubstring(String s) {
int maxLength = 0;
for(int index = 0 ; index<s.length() ; index++){
StringBuffer temp = new StringBuffer(s.substring(index,index+1));
for(int buffer = index+1 ; buffer < s.length() ; buffer++){
// 取当前字符currStr
String currStr = s.substring(buffer,buffer+1);
// 如果temp里面包含了s[buffer],那么结束循环
if(temp.indexOf(currStr)>=0){
if(temp.length()>maxLength)
maxLength = temp.length();
break;
}else{
temp.append(s.charAt(buffer));
}
}
// 如果该子串的长度大于当前最大长度,那么替换为最长长度
if(temp.length()>maxLength){
maxLength = temp.length();
}
}
return maxLength;
}
这个方法非常好理解,但是唯一的问题就是效率非常低,在外层有两层循环,在寻找字符操作时(temp.indexOf(currStr))也要循环一遍,所以该算法的复杂度为O(n^3)
解法2 滑动构造子串
public static int lengthOfLongestSubstring(String s){
// 非空校验
if(s==null || s.isEmpty()){
return 0;
}
int length = s.length();
// 定义滑动标志位:indexOne,indexTwo s[indexOne]~s[indexTwo]之间的字符串组成一个不重复字符的子
// 串
int indexOne = 0 , indexTwo = 0;
int maxLength = 0;
Set<Character> set = new HashSet<>();
while(indexOne < length && indexTwo < length){
// 如果set不包含新字符
if(!set.contains(s.charAt(indexTwo))){
// 那么indexTwo++ ,同时将新字符添加到set中
set.add(s.charAt(indexTwo++));
// 当前子串长度为 indexTwo - indexOne
maxLength = Math.max(maxLength , indexTwo - indexOne);
}else{
set.remove(s.charAt(indexOne++));
}
}
return maxLength;
}
滑动构造子串的意思即通过两个索引indexOne,indexTwo动态构造子串,如果下一个字符没重复,那么indexTwo+1,如果下一个字符已重复,那么indexOne+1。
在最好的情况下,例如输入"abcde"的时候,下一个字符一直是新的字符,那么indexTwo可以一直+1,直到字符串被遍历完,这时候的效率为O(n)。
在最差的情况下,例如输入"bbbbb"的时候,下一个字符一直是重复字符,那么程序一直执行indexTwo+1后indexOne+1的循环,也即indexOne和indexTwo分别遍历了一遍了字符串,那么这时候的效率为O(2n)。
所以综合来看该算法的效率为O(n)。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。