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

leetcode 3. Longest Substring Without Repeating Characters

时间:2019-01-21 00:31:01      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:must   bst   substr   note   方法   ==   pre   map   etc   

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.

解法一:Brute Force
把每两个字母之间是否有重复都判断一遍,如果没有重复就更新x值。
用一个独立的方法来判断是否有重复字母,用上了HashSet的contains来判断重复性
但是这个解法要O(n3),时间太长了,所以不是一个好解法。
class Solution {
    public int lengthOfLongestSubstring(String s) {
        int x=0;
        int l = s.length();
        for(int i =0; i<l; i++) {
            for(int j=i+1; j<=l; j++) {
                if(allUnique(s,i,j)) x = Math.max(x,j-i);
            }
        }
        return x;
    }
    
    public boolean allUnique(String s, int start, int end){
        Set<Character> set = new HashSet<>();
        for(int i =start; i<end; i++) {
            Character ch = s.charAt(i);
            if(set.contains(ch)) return false;
            set.add(ch);
        }
        return true;
    }
}

 

☆ 解法二:和我最初的想法很相似,很好地将我的那个想法实现了出来
用两个指针i和j,j专门指向重复字母的后一个字母
O(n)
 public int lengthOfLongestSubstring(String s) {
        if (s.length()==0) return 0;
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        int max=0;
        for (int i=0, j=0; i<s.length(); ++i){
            if (map.containsKey(s.charAt(i))){ //注意charAt的c是小写!!!
                j = Math.max(j,map.get(s.charAt(i))+1);
            }
            map.put(s.charAt(i),i);
            max = Math.max(max,i-j+1);
        }
        return max;
    }

 




leetcode 3. Longest Substring Without Repeating Characters

标签:must   bst   substr   note   方法   ==   pre   map   etc   

原文地址:https://www.cnblogs.com/jamieliu/p/10296779.html

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