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;

    }

      }

  • 相关阅读:
    Kotlin开发 扩展函数在Android开发中的一些实用例子
    Kotlin开发 使用lambda实现接口回调
    Android开发 Camera2的CaptureRequest属性整理--完善中
    Android开发 Bitmap图像处理详解
    Android开发 Camera预览画面镜像问题
    Android开发 ViewPage2
    windows 服务器更新程序下载-修复漏洞
    JAVA实现数据等分,一个List分成多个List
    List<CourseRecord>转HashMap<Long, List<CourseRecord>>
    模拟服务器1.0——WebServer 、ClientHandler 接收请求、做出响应
  • 原文地址:https://www.cnblogs.com/shisw/p/4367129.html
Copyright © 2011-2022 走看看