题目:
给定一个字符串,请你找出其中不含有重复字符的最长子串的长度。
例:
输入: “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
思路:
使用一个滑动窗口来遍历整个字符串,使用一个数组列表arrayList来储存当前遍历到的最长不重复子字符串。
当遍历到第i个字符s时,
1.若之前遍历到的字符中不包含s,则将s加入arrayList
2.若之前遍历到的字符中已包括字符s,则(1)保存当前arrayList的尺寸,并与当前最大尺寸相比,若大于则更新最大尺寸。(2)将arrayList中包括上一个s和之前的字符全部删除,加入新的s。
3.当遍历结束时,将最后arrayList尺寸再与最大尺寸对比,如有需要则需更新最大值。
代码:
class Solution {
public int lengthOfLongestSubstring(String s) {
if (s==null)
return 0;
int longest = 0;
ArrayList<Character> arrayList = new ArrayList<>();
for (int i = 0; i <s.length(); i++) {
if (arrayList.contains(s.charAt(i))){
int currentLength = arrayList.size();
longest = Math.max(longest,currentLength);
while (arrayList.contains(s.charAt(i))) {
arrayList.remove(0);
}
arrayList.add(s.charAt(i));
}
else {
arrayList.add(s.charAt(i));
}
}
longest=Math.max(longest,arrayList.size());
return longest;
}
}