[LeetCode]3. Longest Substring Without Repeating Characters 最长无重复子串解析。java

来源:互联网 发布:c语言linuxsleep 编辑:程序博客网 时间:2024/06/11 04:02


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.

这里用的不是native method, 因为它虽然直接但是太慢了。O(n3). 因为找的是无重复的子串,因此我们使用Hashset结构来存放已经找到的字符,HashSet中保存的是从某个位置pre到另一个位置res中间的所有字符。hashset 作为一个滑动窗口, 使用这个hashset保存在当前的滑动窗口(i,j)的字符。然后我们向右滑动j,If it is not in the HashSet, we slide j further. Doing so until s[j] is already in the HashSet. At this point, we found the maximum size of substrings without duplicate characters start with index ii. If we do this for all i, we get our answer.

我们需要定义两个变量ans和i,其中ans用来记录最长无重复子串的长度,i指向该无重复子串左边的起始位置,然后我们遍历整个字符串,对于每一个遍历到的字符,如果哈希表中该字符串对应的值为0,说明没有遇到过该字符,则此时计算最长无重复子串,j - i +1,其中j是最长无重复子串最右边的位置,i是最左边的位置,还有一种情况也需要计算最长无重复子串,就是当哈希表中的值小于left,这是由于此时出现过重复的字符,i的位置更新了,如果又遇到了新的字符,就要重新计算最长无重复子串。最后每次都要在哈希表中将当前字符对应的值赋值为i+1。,下面这种解法使用了set,核心算法和上面的很类似,把出现过的字符都放入set中,遇到set中没有的字符就加入set中并更新结果res,如果遇到重复的,则从左边开始删字符,直到删到重复的字符停止:代码如下:

public class Solution {    public int lengthOfLongestSubstring(String s) {        if(s == null || s.length() < 1)          return 0;
         int n = s.length();      Set<Character> set = new HashSet<>();        int ans = 0, i = 0, j = 0;       while (i < n && j < n) {            // try to extend the range [i, j]            if (!set.contains(s.charAt(j))){                set.add(s.charAt(j++));                ans = Math.max(ans, j - i);            }            else {                set.remove(s.charAt(i++));            }        }        return ans;
    }
  }





阅读全文
0 0
原创粉丝点击