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;
        }
    }

    屌啊。

  • 相关阅读:
    js生成点阵字体
    随笔
    html5 textarea 的 placeholder 换行的几种方式
    有物不知其数,三三数之剩二,五五数之剩三,七七数之剩二。问物几何?
    javascript 水仙花数
    避免url传值字符串sjstr过长,使用from表单【隐藏域】post提交
    图表转换
    highcharts 显示点值的效果
    导出报表
    JQuery ----文档处理
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10204173.html
Copyright © 2011-2022 走看看