题目:
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.
解法1:
public class Solution {
public int lengthOfLongestSubstring(String s) {
int MaxLen = 1;//最大长度
String maxString = null;//最大字符串
if(s.length()==0||s.length()==1)//如果字符串长度为0或者1 直接返回
return s.length();
char[] sstring = s.toCharArray();//把字符串转化为字符数组
java.util.List<Character> list=new ArrayList<Character>();
for(int i = 0; i <s.length(); i++)
{
if(MaxLen>s.length()-i)
return MaxLen;
if(list.contains(sstring[i]))
{
int tlen = list.size();
MaxLen = MaxLen>tlen?MaxLen:tlen;
int index = list.indexOf(sstring[i]);
list = list.subList(index+1, list.size());
}
list.add(sstring[i]);
}
if(list.size()>MaxLen)
return list.size();
return MaxLen;
}
}
初步想到的解法是这个,把最长的放在list里,如果出现重复的 就把前面的去掉。保存最大长度的值。最后当最大长度大于剩余,返回。
本地测试没有问题,结果放在上面出现
容我在想一想解决方法啊。
看了一位大大的解题思路,顿时觉得茅塞顿开。
http://blog.csdn.net/linhuanmars/article/details/19949159
采用线性的方法,就是维护一个set窗口,每次检查窗口里面有无重复,有的话进行删除,
时间复杂度空间复杂度均为O(n);不错,学习到了
public static int lengthOfLongestSubstring(String s) {
int MaxLen = 0;//最大长度
String maxString = null;//最大字符串
if(s.length()==0||s.length()==1)//如果字符串长度为0或者1 直接返回
return s.length();
int left = 0;
int right = 0;
HashSet<Character> set = new HashSet<Character>();
while(right<s.length())
{
if(set.contains(s.charAt(right)))
{
if(MaxLen < right - left)
{
MaxLen = right - left;
}
while(s.charAt(left)!=s.charAt(right))
{
set.remove(s.charAt(left));
left++;
}
left++;
}
else {
set.add(s.charAt(right));
}
right++;
}
MaxLen = Math.max(MaxLen, right-left);
return MaxLen;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成的方法存根
String s = "abcdefghijklmnopqrstuvwxyzdefg";
int k = lengthOfLongestSubstring(s);
System.out.println(k+"\t\t\t");
}