03刷LeetCode

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);
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值