摘要:建立数组,存储个字符最近一次出现的位置。首次出现某字符时,其位置标记为,并用无重复字符计数器记录无重复字符的长度,再在更新其最大值。循环完整个字符串后,返回最大值。
Problem
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.
Note建立int数组ch[],存储256个字符最近一次出现的位置。首次出现某字符a时,其位置标记为ch[a],并用无重复字符计数器count记录无重复字符的长度,再在max更新其最大值。
当出现重复字符a时,从无重复字符计数器count中减去两个重复字符之间的长度(ch[a]-start),并更新start为最后一个(任意)重复字符上一次出现的位置,然后更新重复字符的位置ch[a]。
循环完整个字符串后,返回最大值max。
举例说明:
"pwwkewk" start = 0, count = 0, max = 0
i = 0:
a = "p" ch["p"] = 0 + 1 = 1 count = 1 max = 1
i = 1:
a = "w" ch["w"] = i + 1 = 2 count = 2 max = 2
i = 2:
a = "w" ch["w"] = 2 > start = 0 count = count - (ch["w"] - start) = 2 - (2 - 0) = 0 start = 2 ch["w"] = 2 + 1 = 3 count = 1 max = 2
i = 3:
a = "k" ch["k"] = 3 + 1 = 4 count = 2 max = 2
i = 4:
a = "e" ch["e"] = 5 count = 3 max = 3
i = 5:
a = "w" ch["w"] = 3 > start = 2 count = count - (ch["w"] - start) = 3 - (3 - 2) = 2 start = 3 ch["w"] = 6 count = 2 + 1 = 3 max = 3
i = 6:
a = "k" ch["k"] = 4 start = 3 count = count - (ch["k"] - start) = 3 - (4 - 3) = 2 start = 4 ch["k"] = 7 count = 3 max = 3Solution
public class Solution { public int lengthOfLongestSubstring(String s) { int[] ch = new int[256]; int max = 0, count = 0, start = 0; for (int i = 0; i < s.length(); i++) { char a = s.charAt(i); if (ch[a] > start) { count -= ch[a] - start; start = ch[a]; } ch[a] = i+1; max = Math.max(max, ++count); } return max; } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/66027.html
摘要:哈希表是最自然的想法。在遍历字符串时,我们先根据哈希表找出该字符上次出现的位置,如果大于等于子字符串首,便更新子字符串首。结束后,将该字符新的位置放入哈希表中。 Longest Substring Without Repeating Characters 最新更新解法:https://yanjia.me/zh/2018/12/... Given a string, find the ...
Problem 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...
摘要:题目详情题目要求输入一个字符串,我们要找出其中不含重复字符的最长子字符串,返回这个最长子字符串的长度。对于字符串中的每一个字符,先判断中是否已经存在这个字符,如果不存在,直接将添加到,如果已存在,则新的字符串就从不含前一个字符的地方开始。 题目详情 Given a string, find the length of the longest substring without repe...
摘要:哈希表法双指针法只有当也就是时上面的循环才会结束,,跳过这个之前的重复字符再将置为 Problem Given a string, find the length of the longest substring without repeating characters. Example For example, the longest substring without repeat...
摘要:解题思路本题借助实现。如果字符未出现过,则字符,如果字符出现过,则维护上次出现的遍历的起始点。注意点每次都要更新字符的位置最后返回时,一定要考虑到从到字符串末尾都没有遇到重复字符的情况,所欲需要比较下和的大小。 Longest Substring Without Repeating CharactersGiven a string, find the length of the lon...
阅读 1182·2021-10-18 13:32
阅读 2218·2021-09-24 09:47
阅读 1253·2021-09-23 11:22
阅读 2384·2019-08-30 14:06
阅读 507·2019-08-30 12:48
阅读 1936·2019-08-30 11:03
阅读 457·2019-08-29 17:09
阅读 2371·2019-08-29 14:10