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.
解题思路:利用滑动窗口来获取字符并且判断出最大的长度。
class Solution {
public int lengthOfLongestSubstring(String s) {
ArrayList<Character> a=new ArrayList<Character>();
if(s.length()>0)
{
a.add(s.charAt(0));
int max=1;
int left=0;
for(int i=1;i<s.length();i++)
{
if(a.contains(s.charAt(i)))
{
left=a.indexOf(s.charAt(i));
for(int j=0;j<=left;j++)
{
a.remove(0);
}
a.add(s.charAt(i));
if(a.size()>max)
max=a.size();
}
else
{
a.add(s.charAt(i));
if(a.size()>max)
max=a.size();
}
}
return max;
}
else
return 0;
}
}