003_LeetCode_3 Longest Substring Without Repeating Characters 题解

来源:互联网 发布:华语网络女歌手排行榜 编辑:程序博客网 时间:2024/06/09 17:24

Descripton


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


Examples:


  • 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.

返回一个字符串中,不包含重复元素的连续子序列的长度。


解:


使用HashMap,以字符串对应的元素作为key,下标作为value。遍历字符串,判断当前元素是否已经存在于哈希表中:

  • 若存在则,删除上次存入的下标以及该下标之前的元素;将当前元素存入哈希表,更新起始的遍历位置和子串长度。

  • 若不存在,则将当前元素存入哈希表,子串长度加一,并于最大子串长度比较。


java代码:


class Solution {    public int lengthOfLongestSubstring(String s) {        if (s == null) return 0;        HashMap<Character, Integer> map =  new HashMap<Character, Integer>();        int start = 0, maxLen = 0, subLen = 0;        for (int i = 0; i < s.length(); i++) {            if (!map.containsKey(s.charAt(i))){                map.put(s.charAt(i), i);                subLen++;                if (subLen > maxLen) maxLen = subLen;            }else {                int index = map.get(s.charAt(i));                for (int j = start; j <= index; j++) {                    map.remove(s.charAt(j));                }                map.put(s.charAt(i), i);                start = index + 1;                subLen = i - index;            }        }        return maxLen;    }}
阅读全文
0 0