码迷,mamicode.com
首页 > 其他好文 > 详细

3. Longest Substring Without Repeating Characters

时间:2019-01-01 11:15:59      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:unique   false   long   enc   The   als   color   try   div   

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

 

3. Longest Substring Without Repeating Characters

标签:unique   false   long   enc   The   als   color   try   div   

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10204173.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!