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;

    }

      }

  • 相关阅读:
    Linux ls
    Linux wc | 简单的字符数行数统计工具
    Linux less | 功能丰富的终端文本浏览器
    POSIX正则表达式 | BRE和ERE
    docker连不上私有仓库Harbor
    血泪史: k8s Initial timeout of 40s passed.
    无法访问k8s.gcr.io下载镜像问题解决办法
    Galera_Cluster_Mysql部署
    解决MobaXterm自动断开连接,亲测有效~
    Ubuntu使用dpkg查看与修改architecture的用法
  • 原文地址:https://www.cnblogs.com/shisw/p/4367129.html
Copyright © 2011-2022 走看看