zoukankan      html  css  js  c++  java
  • LeetCode(3):Longest Substring Without Repeating Characters

    Longest Substring Without Repeating Characters:Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

    题意:求最长非重复字串。

    思路:采用双指针进行解决,利用一个数组保存字符是否出现,从前向后遍历数组,如果遇到已存在的字符,应该回退到这个字符出现的下一个位置重新开始统计,同时要更新数组。

    代码

    public class Solution {
        public int lengthOfLongestSubstring(String s) {
            if(s==null||s.length()==0) return 0;
            int res = 1;
            boolean[] exist = new boolean[256];
            int start = 0;
            for(int i =0;i<s.length();i++){
                char ch = s.charAt(i);
                if(exist[ch]){
                    res = Math.max(res,i-start);
                    for(int k=start;k<i;k++){
                        if(s.charAt(k)==ch){
                            start = k + 1;
                            break;
                        }
                        exist[s.charAt(k)] = false;
                    }
                }else{
                    exist[ch] = true;
                }
            }
            res = Math.max(res,s.length() - start);
            return res;
        }
    }
  • 相关阅读:
    react-dnd例子代码学习记录
    GitKraken使用记录
    Table-dnd-tree代码分析
    umi-request请求码200,但是response是网页
    MyBatis-Plus配置输出日志
    PAT甲级1021解法
    PAT甲级1020解法
    PAT甲级1019解法
    PAT甲级1017解法
    PAT甲级1018解法
  • 原文地址:https://www.cnblogs.com/Lewisr/p/5255359.html
Copyright © 2011-2022 走看看