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;

    }

      }

  • 相关阅读:
    windows10装机小记
    Linus Benedict Torvalds hate FUD
    营销文章good
    商城趣聊4
    商城趣聊3
    商城趣聊2
    商城趣聊1
    temp
    学习代码检视方法 (摘自某图片)
    xilinx sdk闪退问题
  • 原文地址:https://www.cnblogs.com/shisw/p/4367129.html
Copyright © 2011-2022 走看看