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

    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 subsequence and not a substring.

     

    public class LongestSubstringWithoutRepeatingCharacters {

         public int lengthOfLongestSubstring(String str) {
             Set<Character> sets = new HashSet<Character>();
            
             int max = 0;
            
             int start=0;
             for(int i=0,len=str.length();i<len;i++){
                 char cha = str.charAt(i);
                
                 if(sets.contains(cha)){
                     while(str.charAt(start)!=str.charAt(i)){
                         sets.remove(str.charAt(start));
                         start++;
                     }
                    
                     start++;
                 }else{
                     sets.add(cha);
                 }
                 max=i-start>max?i-start:max;
                 System.out.println(str.substring(start, i));
             }
            
             return max;
         }
        /**
         * @param args
         */
        public static void main(String[] args) {
            LongestSubstringWithoutRepeatingCharacters l = new LongestSubstringWithoutRepeatingCharacters();
            int len = l.lengthOfLongestSubstring("abcacddcefbb");
            System.out.println(len);
        }

    }

    使用集合Set不能包含重复元素的方法,从字符串的开始位置依次往后判断,如果存在重复元素,将子字符串的开始位置移动到重复元素位置再次判断。

    public int lengthOfLongestSubstring(String s) {

    if(null!=s){

    int start = 0,end = 0;

    int len = s.length();

    int size = 0;

    while(end<len){

    char c = s.charAt(end++);

    String str = s.substring(start, end-1);

    if(-1 != str.indexOf(c)){

    start = s.indexOf(c, start)+1;

    }

     

    if(end-start > size){

    size = end - start;

    System.out.println(size + "==" + s.substring(start, end));

    }

     

    }

    System.out.println(s.substring(start));

    return size;

    }else{

    return 0;

    }

      }

  • 相关阅读:
    Serverless 架构到底要不要服务器?
    Serverless 在 SaaS 领域的最佳实践
    20 行代码:Serverless 架构下用 Python 轻松搞定图像分类和预测
    创业公司用 Serverless,到底香不香?
    如何通过 Serverless 轻松识别验证码?
    Serverless 是一种思想状态
    都 2021 年了,Serverless 能取代微服务吗?
    从零入门 Serverless | 架构的演进
    Serverless 的价值
    实验楼前后端代码
  • 原文地址:https://www.cnblogs.com/shisw/p/4367129.html
Copyright © 2011-2022 走看看