LeetCode(3):无重复字符的最长子串

题干

ex

求解

  • 根据题干的描述,要确定最长无重复字符字串的长度,我们可以使用一个队列;
    依次向队列中加入字符,若不存在在入队,反之,出队(直至去除重复字符)
class Solution {
	public int lengthOfLongestSubstring(String s) {
		if(s.trim().isEmpty()&&(!s.isEmpty()))return 1;
		if(s.isEmpty())return 0;
		Queue<Character> q = new LinkedList<Character>();
		int maxLength=1,length=1;
		q.add(s.charAt(0));
		
		for(int i=1;i<s.length();i++) {
			if(q.contains(s.charAt(i))) {
				while(!q.element().equals(s.charAt(i))) {
					q.remove();
					length--;
				}
				q.remove();
				length--;
			}
			q.add(s.charAt(i));
			length++;
			if(length>maxLength) {
				maxLength=length;
			}
		}
		
		return maxLength;
		
	}
}

result

官方题解

  • 遍历给定字符串 s 的所有可能的子字符串并调用函数 allUnique。 如果事实证明返回值为 true,那么我们将会更新无重复字符子串的最大长度的答案。
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;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值