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;

    }

      }

  • 相关阅读:
    200. Number of Islands 200.岛屿数(可以形状一样)
    695. Max Area of Island最大岛屿面积
    springboot如何在项目启动时初始化资源
    springboot之集成Memcached
    springboot之spring-boot-admin对springboot服务进行监控
    springboot之集成FastDFS
    springboot之上传文件
    springboot之整合shiro-登录认证和权限管理
    springboot 如何测试打包部署
    springboot之Mongo
  • 原文地址:https://www.cnblogs.com/shisw/p/4367129.html
Copyright © 2011-2022 走看看