Leetcode - Longest Substring Without Repeating Characters

Question

Given a string, find the length of the longest substring without repeating characters.

For example,

Given “abcabcbb”, the answer is “abc”, which the length is 3.

Given “bbbbb”, the answer is “b”, with the length of 1.

Given “pwwkew”, 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.

Java Code

public int lengthOfLongestSubstring(String s) { 
    int count = 0;//当前子串中不重复的长度
    int pos = 0;//当前子串的起始位置
    int max = 0;
    String ch = new String();
    String subStr = new String();

    for(int j = 0; j < s.length(); ++j) {
        ch = s.substring(j, j+1);
        subStr = s.substring(pos, j);
        if (subStr.contains(ch))
            pos += subStr.indexOf(ch) + 1;//新子串的长度从重复字符的下一个位置开始统计

        count = j - pos + 1;
        if(count > max)
            max = count;
    }
    return max;
}

说明

  • 本文解法的时间复杂度为O(n);

  • 游标pos用来指示当前子串的起始位置,用于计算当前不重复子串的长度,且它总是指向上一次出现重复字符的下一位;

  • 当遇到重复字符时,索引j不需要回溯到当前子串中重复字符的下一位,因为位于pos和j之间的字符已经验证过不会重复;

  • 本题也可以使用collection解决,大致思路是:

    1. 遍历字符串,往HashMap中依次存入<字符,索引>键值对
    2. 判断新加入的字符是否已经在HashMap中存在
      • 如果不存在则存入;
      • 如果存在但其下标小于pos,则表明该字符不在当前子串的范围之内,直接覆盖掉该字符的索引;
      • 如果存在且其下标不小于pos,则当前子串出现重复字符,取出该字符的索引,加上1再赋给pos,用新的键值对覆盖掉HashMap中该字符的索引
    3. 继续统计当前子串的不重复长度,或者进入下一个不重复子串的统计

你可能感兴趣的:(LeetCode,HashMap,substring,longest)