Description
Given a string, find the length of the longest substring without repeating characters.
Examples
Example1:
Input: “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.
Example2
Input: “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.
Example3
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.
题目解释
其实就是查找最长没有重复字符的子串
解题思路
想到的就是动态规划
新建了一个Set集合用来存储当前符合规定的子串,一个max存最大字串长度,temp存当前子串长度(突然发现temp可以不要,直接用tset.size()来代替……当时怕不是傻的)
然后就是动态规划那一套
如果当前未重复子串中含有下一个要放进来的字符,就进行如下操作:
- 新建一个迭代器,用于删除重复字符及其前面所有字符
- 循环查找重复字符
- 只要不是重复字符就删去,如果碰到了重复字符就退出循环
- 退出循环后更新max和temp
然后进行常规的add字符,更新temp的操作
解题代码
class Solution {
public int lengthOfLongestSubstring(String s) {
int i, j, max = 0, temp = 0;
Set<Character> tset = new LinkedHashSet<>();
for(i = 0; i < s.length(); i++){
if(tset.contains(s.charAt(i))){
j = 0;
Iterator<Character> it = tset.iterator();
while (it.hasNext()) {
Character del = it.next();
it.remove();
j++;
if(del == s.charAt(i))
break;
}
if(temp > max)
max = temp;
temp = temp - j;
}
tset.add(s.charAt(i));
temp ++;
}
if(temp > max)
max = temp;
return max;
}
}
其他
自己写的代码,改了超级久,总结下来两个原因,一个迭代器一个set
关于迭代器因为不经常用所以不是很清楚
搜了半天稍微了解了一点
初始化方式是iterator<Object> it = set_list_map_name_of_type_object iterator()
it.next()会返回当前值并让it跳到下一跳,同时使用it.remove()会删除当前记录
如[0, 1],连续调用next和remove的时候会读取0并删除0,且会生成保护记录,在调用next之前都不能再次执行remove
之前以为在remove之后需要重新定位,其实是不需要的,且重新定位需要时间,在去掉重新定位之后,速度提升了4ms
然后是set
问题出在set的初始化,千万不要用HashSet,千万不要用HashSet,千万不要用HashSet!
因为HashSet的存储方式是是通过散列法的机制来存储信息的,不是按照你放入元素的顺序存储的!所以在一个不能debug的leetcode(或者其实能de但我不知道在哪儿)中需要通过反复用return查看输出值来抓虫orz,实在太艰辛了!
补充一下,按照放入顺序存储的set类型是LinkedHashSet
之前因为一直找不到原因心灰意冷用了list加set的方式先ac一次,由于每次都要新建set所以速度超级慢,代码放一下做个记录吧QuQ
class Solution {
public int lengthOfLongestSubstring(String s) {
int i, j, max = 0, temp = 0;
List<Character> tlist = new ArrayList<>();
for(i = 0; i < s.length(); i++){
Set<Character> tset = new HashSet<>(tlist);
int check = tset.size();
tset.add(s.charAt(i));
if(check == tset.size()){
for(j = 0; tlist.get(0) != s.charAt(i) ;j++){
tlist.remove(0);
}
tlist.remove(0);
if(temp > max)
max = temp;
temp = temp - j - 1;
}
tlist.add(s.charAt(i));
temp ++;
}
if(temp > max)
max = temp;
return max;
}
}
本来想看看leetcode给出的solution,但是好晚了,而且solution有好多……等有时间过完再更新~