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.
思路一,我自己的思路采用的是hashmap来保存每次出现的字符,当出现重复字符的时候,就记录这段的最长,然后重新开始。但是这样很浪费时间,重复了一些步骤。
class Solution {
public int lengthOfLongestSubstring(String s) {
//采用hashmap的简单解法
int result = 0;
//从第一个字符开始
for(int i = 0; i < s.length(); i++)
{
Map<Character, Integer> hmap = new HashMap<>();
int count = 0;
//计算从第一个字符开始的不重复子串
for(int j = i ; j < s.length(); j++)
{
if(!hmap.containsKey(s.charAt(j)))
{
hmap.put(s.charAt(j),1);
count++;
}
else
break;
}
//保存当前最大的子串
if(count >= result)
result = count;
}
return result;
}
}
思路二:开辟一个能容纳所有字母ASCII码大小的数组,用字母当下标,值当出现的位置,用一个指针来指示从不重复的位置开始。
class Solution {
public int lengthOfLongestSubstring(String s) {
int[] m = new int[256];
Arrays.fill(m, -1);
int res = 0, left = -1;
for (int i = 0; i < s.length(); ++i) {
//当出现重复的时候,从这个重复的位置重新开始,实际上是从下一个位置开始的
left = Math.max(left, m[s.charAt(i)]);
m[s.charAt(i)] = i;//字母当下标,位置当值
//求每次不重复的子串
res = Math.max(res, i - left);
}
return res;
}
}