Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.
Given "bbbbb"
, the answer is "b"
, with the length of 1.
Given "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequenceand not a substring.
翻译:给一个String,返回它最长的且没有重复字符的长度
例子:给“abcabcbb”,答案为“abc”,返回长度是3;
给“bbbbb”,答案为“b”,返回长度是1;
给“pwwkew”,答案为“wke”,返回长度是3;
思路:利用HashSet不重复特点,把字符串分为字符存入HashSet,把不没有重复的第一个值坐标赋值为star,遍历字符串,当发现HashSet存在相同当前字符值,则判断当前值是否等于star,不等则把star自增,直到star等于当前字符,然后重新开始第二轮遍历,直到结束
代码:
package test;
import java.util.HashSet;
public class LongestCharacters {
public int lengthOfLongestSubstring(String s){
char star=0;//没有重复的第一个字符坐标
int index=0;//当前字符坐标
int max=1;//最大长度
HashSet<Character> hs = new HashSet<Character>();
while(index<s.length()){
if(hs.contains(s.charAt(index))){ //如果HashSet里面包含当前字符的相同值
if(max<index-star){
max = index - star;
}
while(s.charAt(star)!=s.charAt(index)){ //如果当前字符的值不等于star下标的值,则把HashMap重复值前面的字符全部移除
hs.remove(s.charAt(star));
star++;
}
star++;//让star下标移动到当前下标
}
else{
hs.add(s.charAt(index));
}
index++;
}
max = Math.max(max, index-star);
return max;
}
public static void main(String[] args) {
String s = "pwwkew";
int a = new LongestCharacters().lengthOfLongestSubstring(s);
System.out.println(a);
}
}