0
点赞
收藏
分享

微信扫一扫

26.(★)剑指 Offer 48. 最长不含重复字符的子字符串

星巢文化 2022-02-28 阅读 43

题目描述:请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。

思路:

代码:

1)手写代码:

class Solution {
    public int lengthOfLongestSubstring(String s) {
        //每次记录个最大值,对比留最大
        int i = 0;
        Queue<Character> queue = new LinkedList<>();//记录最大字串
        Set<Character> set = new HashSet<>();//判断是否已经包含
        char[] ch = s.toCharArray();
        for(char c : ch){
            if(!set.contains(c)){//不包含就添加
                set.add(c);
                queue.add(c);
            }else if(set.contains(c)){//出现包含,就先得到最大值
                i = Math.max(queue.size(),i);
                while(!(c == queue.peek())){//循环弹出包含的字符之前的内容,同时要从set中remove;
                    set.remove(queue.poll());
                }
                queue.add(c);
                queue.poll();
            }
        }
        return Math.max(i,queue.size());
    }
}

 2)答案代码:

举报

相关推荐

0 条评论