LeetCode 3: Longest Substring Without Repeating Characters

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/itnerd/article/details/82718324

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.

my solution

class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s.length() == 0){
            return 0;
        }
        int curhead = 0;
        int curlength = 1;
        int maxlength = 1;

        Map<Character, Integer> charLocation= new HashMap<>();
        charLocation.put(s.charAt(curhead),curhead);

        for (int i = 1; i < s.length(); ++i){
            int oldloc = -1;
            if(charLocation.containsKey(s.charAt(i))){
                oldloc = charLocation.get(s.charAt(i));
            }
            if(oldloc < curhead){
                curlength++;
                maxlength = maxlength>curlength?maxlength:curlength;

            }else{
                curhead = oldloc+1;
                curlength = i-oldloc;
            }
            charLocation.put(s.charAt(i),i);
        }
        return maxlength;
    }
}

逻辑清晰一点的解法:

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length(), ans = 0;
        Map<Character, Integer> map = new HashMap<>(); // current index of character
        // try to extend the range [i, j]
        for (int j = 0, i = 0; j < n; j++) {
            if (map.containsKey(s.charAt(j))) {
                i = Math.max(map.get(s.charAt(j)), i);
            }
            ans = Math.max(ans, j - i + 1);
            map.put(s.charAt(j), j + 1);
        }
        return ans;
    }
}

或者用int array 替代 hashmap

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

猜你喜欢

转载自blog.csdn.net/itnerd/article/details/82718324