不含重复字符的子字符串

/*
*给定一个字符串,在不重复字符的情况下查找最长子字符串的长度。
*Input: "abcabcbb"
*Output: 3
*Explanation: The answer is "abc", with the length of 3.
*==========================================================
*Input: "bbbbb"
*Output: 1
*Explanation: The answer is "b", with the length of 1.
*=========================================================
*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.
*/

参考法1:

滑动窗口思想,用到HashSet     [i,j)   当set.contains(s.charAt(j))   移除set中第i个字符,  

class Solution {
public int lengthOfLongestSubstring(String s) {
Set<Character> set=new HashSet<>();
int i=0;
int j=0;
int n=s.length();
int ans=0;
while(i<n && j<n){
if(!set.contains(s.charAt(j))){
set.add(s.charAt(j++));
ans=Math.max(ans,j-i);
}
else{
set.remove(s.charAt(i++));
}
}
return ans;
}
}

参考法2:没有法一清楚。

public class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length();
int ans = 0;
for (int i = 0; i < n; i++)
for (int j = i + 1; j <= n; j++)
if (allUnique(s, i, j)) ans = Math.max(ans, j - i);
return ans;
}

public boolean allUnique(String s, int start, int end) {
Set<Character> set = new HashSet<>();
for (int i = start; i < end; i++) {
Character ch = s.charAt(i);
if (set.contains(ch)) return false;
set.add(ch);
}
return true;
}
}

猜你喜欢

转载自www.cnblogs.com/jian2014/p/10288100.html