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.
选出不重复的最长子串。
首先想到的是一个很土办法,把字符串中所有的子串全部存到一个list中,然后遍历每个子串,看是否有重复字母,如果没有,就存到map中,最后遍历map得到长度最大的子串,可惜这个方法耗时太长,提交不通过,先记录下这个土办法,明天有空在想想其他的思路。
public static int lengthOfLongestSubstring(String s) {
if(s.length() == 1){
return 1;
}
List<String> list = new ArrayList<String>();
for(int i = 0; i<s.length();i++){
for(int j = i+1;j<=s.length();j++) {
list.add(s.substring(i, j));
}
}
Map<Integer,String> map = new HashMap<Integer,String>();
for (String string : list) {
List<String> list1 = new ArrayList<String>();
boolean flag = false;
for(int i = 0; i<string.length();i++){
if(list1.contains(string.substring(i, i+1))){
flag = true;
break;
}else {
list1.add(string.substring(i, i+1));
}
}
if(!flag){
map.put(string.length(), string);
}
}
int max = 0;
for(Integer in : map.keySet()){
if(max<in){
max = in;
}
}
return max;
}