leetcode解题之3. Longest Substring Without Repeating Characters Java版(最长子串长度)

来源:互联网 发布:秦夕妍幼年捏脸数据 编辑:程序博客网 时间:2024/06/06 07:44

3. Longest Substring Without Repeating Characters

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 asubsequence and not a substring.

该函数返回一个maxlen即最长子串的长度,用一个Deque存放字母以及其对应下标,利用for循环里的i遍历该string,则对于每个字母,有以下两种情况:
 (1)若当前字母不在Deque中则放入,用一个len来记录当前符合条件的子串长度,并把其与最终要返回的maxlen比较,若len较大则其替换maxlen。
(2)若当前字母在已经在Deque中,我们将删掉上一个与它相同值之前的所有内容(包含那个值本身),然后重新开始记录一个新的符合要求的子串。

拓展:如果需要求最长子串而不是长度,只需要一个临时变量记录子串即可,调用string.subString方法

public int lengthOfLongestSubstring(String s) {if (s == null || s.length() == 0)return 0;// pre指向与最后加入的字符不同的位置int pre = 0;int i = 0;int max = 0;int len = s.length();// 需要头部删除使用双端队列Deque<Character> dq = new LinkedList<>();while (i < len) {Character c = s.charAt(i);if (!dq.contains(c)) {dq.addLast(c);i++;} else {// 此时pre和i指向字符相同max = Math.max(max, i - pre);while (s.charAt(pre) != c) {dq.removeFirst();pre++;}// 注意删除最后一个与c相同的字符// 删除字符,但是i未变,下一轮循环能把i下标的字符加入到队列dq.removeFirst();// 跳过相等的字符pre++;}}// 当字符串无重复时,max还是0,则需要更新max = Math.max(max, i - pre);return max;}




0 0