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.

    Example 1:

    Input: "abcabcbb"
    Output: 3 
    Explanation: The answer is "abc", with the length of 3. 
    

    Example 2:

    Input: "bbbbb"
    Output: 1
    Explanation: The answer is "b", with the length of 1.
    

    Example 3:

    Input: "pwwkew"
    Output: 3
    Explanation: 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.

    SOlution 1: Brute force
    class Solution {
        public int lengthOfLongestSubstring(String s) {
            int ln = s.length();
            int res = 0;
            for(int i = 0; i < ln; i++){
                for(int j = i+1; j <=ln; j++){
                    if(isUnique(s, i, j))res = Math.max(res, j-i);
                }
            }
            return res;
        }
        public  boolean isUnique(String st, int start, int end){
                ArrayList<Character> list = new ArrayList<Character>();
                for(int i = start; i < end; i++){
                    Character ch = st.charAt(i);
                    if(list.contains(ch)) return false;
                    list.add(ch);
                }
                return true;
            }
    }
    

      主程序重用两层for loop保证每个组合可以被检查,用什么检查呢?用isUnique method。然后submit,Time limit Exceeded。。

    SOlution2:

    public class Solution {
        public int lengthOfLongestSubstring(String s) {
            int n = s.length(), ans = 0;
            int[] index = new int[128]; // current index of character
            // try to extend the range [i, j]
            for (int j = 0, i = 0; j < n; j++) {
                i = Math.max(index[s.charAt(j)], i);
                ans = Math.max(ans, j - i + 1);
                index[s.charAt(j)] = j + 1;
            }
            return ans;
        }
    }

     上面是贪心法,一刷并没有看懂。思路是这样的:

    class Solution {
        public int lengthOfLongestSubstring(String s) {
            int[] dict = new int[256];
            Arrays.fill(dict, -1);    
            int max_len = 0;
            for(int i = 0, start = 0; i < s.length(); i++){   
               start = Math.max(start, dict[s.charAt(i)] + 1);
               max_len = Math.max(max_len, i - start + 1);//每次最大长度都更新
               dict[s.charAt(i)] = i;
            }
            return max_len;
        }
    }

    屌啊。

  • 相关阅读:
    MicroPython实例之TPYBoard v102炫彩跑马灯WS2812B
    MicroPython实例之TPYBoardv102自动浇花系统
    Micropython实例之DIY超声波避障小车
    MicroPython支持图形化编辑了:Python Editor带你轻松玩转MicroPython
    潍坊首个小学“教育创客空间”落户呼家庄小学 萝卜(创客)教育走进小学课堂
    Micropython TPYBoard I2C的用法
    JDK5.0新特性-反射
    JDK5.0新特性-枚举
    JDK5.0新特性-泛型
    JDK5.0新特性-静态导入
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10204173.html
Copyright © 2011-2022 走看看