003_LongestSubstringWithoutRepeatingCharacters

/***
 *
 * 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.
 *
 *
 */
/***
* 關鍵:
* 先遍歷一遍放進hashmap,所以複雜度是O(n)
*
*/
public class N003_LongestSubstringWithoutRepeatingCharacters {
        /***
     * 使用HashMap記錄字符上次出現的位置
     * 用pre記錄最近重複字符出現的位置
     * 則i(當前位置)-pre就是當前字符最長無重複字符的長度
     * 取最大的就是字符串的最長無重複字符的長度
     *
     * 時間複雜度:O(n)
     */
    public static int lengthOfLongestSubstring(String str) {
        if (str == null || str.length() < 1)
            return 0;

        // 記錄字符上次出現的位置
        HashMap<Character, Integer> map = new HashMap<>();
        int max = 0;
        // 最近出現重複字符的位置
        int pre = -1;

        for (int i = 0, strLen = str.length(); i < strLen; i++) {
            Character ch = str.charAt(i);
            Integer index = map.get(ch);
            if (index != null)
                pre = Math.max(pre, index);     //這一步很關鍵,取前一個相同字符位置,而不是後一個;後一個字符還有可能成爲字串的元素
            max = Math.max(max, i - pre);
            map.put(ch, i);
        }

        return max;
    }

    public static void main(String args[]) {
        String input = "nevereverbeacoder";

        int len = lengthOfLongestSubstring(input);
        System.out.println(len);

    }
}
本站公眾號
   歡迎關注本站公眾號,獲取更多信息