Description[This block is from leetcode.com]
3. Longest Substring Without Repeating Characters
Medium
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.
My answer(有待继续考究-用力挠头中):
class Solution {
public int lengthOfLongestSubstring(String s) {
//int len;
int flag0 = 0;
int flag1;
//ArrayList dif = new ArrayList();
List<Integer> dif = new ArrayList<Integer>();
String result = "";
//String store = "";//to store the result
char ch;
String chStr;
//ch = s.charAt(0);
for(int i = 0; i < s.length(); i++){
//to concat the letter
ch = s.charAt(i);
chStr = String.valueOf(ch);
result = result.concat(chStr);
//to check whether previous string has the letter or not
for(int j = 0; j< i; j++ ){
char ch1 = result.charAt(j);
//if(i != j){
if (ch1 == ch){
flag1 = i;
//dif = flag0 - flag1;
dif.add(flag1 - flag0);
//result = result.substring(0, result.length()-1);
flag0 = flag1;
break;
}
// }
}//end inner for
}//end outer for
return Collections.max(dif);
}
}
我的思路是,给出现重复的两个字母处打标,即flag0和flag1(第一次打完标求出差值之后,就要做好准备打第二次标,即此时flag0要移动到flag1的位置了),那么差值就是substring的长度;把所有的差值存储起来,最后里面的最大值就是longest substring。
当然,我觉得我这样的做法很愚蠢,比如明智一点的用map做,因为map中有一个函数是containkey,可以直接在map中查找是否有相同的元素,返回boolean值,这样子就免去了从string中逐一查找char的麻烦。
BTW,我的上述方法自始至终一直是使用一个string,并且用的该string的索引,所以和map的方法在index方面应该差距不大。
我的代码测试很成功,description给出的三个例子在run code之后得出答案都是正确的;但是当提交的时候总是出现神奇的错误。。。所以提交一直没有通过,如图:
现在也没有弄清楚原因。。。。?♀️挠头
update
如下情况测试不通过:"" (无字符情况), "a"(单字符情况), "au"(字符串里不重复的情况)
出现问题的原因是inner for loop,在字符串里不重复时,并不会进入这个循环。
所以我的做法很麻烦,使用map做或许会柳暗花明。