LeetCode(3) - Longest Substring Without Repeating Characters
2017-03-12 13:56
477 查看
https://leetcode.com/problems/longest-substring-without-repeating-characters/#/description
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given
which the length is 3.
Given
with the length of 1.
Given
with the length of 3. Note that the answer must be a substring,
a subsequence and not a substring.
Solution:
整体思路是不断地记录唯一的char,当出现重复时,计算Length并清空记录。
由于用for来做,所以记得在最后的时候做最后的检测。
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.
Solution:
整体思路是不断地记录唯一的char,当出现重复时,计算Length并清空记录。
由于用for来做,所以记得在最后的时候做最后的检测。
public int lengthOfLongestSubstring(String s) { int maxLength = 0; Set<Character> dict = new HashSet<>(); int start = 0; char[] chars = s.toCharArray(); for(int i = 0; i < chars.length; i++) { if(!dict.add(chars[i])) { int length = i - start; if(length > maxLength) { maxLength = length; } start = i; dict.clear(); } } //last check maxLength = maxLength > s.length() - start ? maxLength : s.length() - start; return maxLength; }
相关文章推荐
- LeetCode3:Longest Substring Without Repeating Characters
- 【LeetCode】Longest Substring Without Repeating Characters
- LeetCode-Longest Substring Without Repeating Characters
- LeetCode 3 Longest Substring Without Repeating Characters
- [leetcode]Longest Substring Without Repeating Characters
- [Leetcode-3] Longest Substring Without Repeating Characters
- Leetcode Longest Substring Without Repeating Characters解题报告
- LeetCode之Longest Substring Without Repeating Characters
- Leetcode - Longest Substring Without Repeating Characters
- leetcode - Longest Substring Without Repeating Characters
- LeetCode Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters Leetcode Python Java
- Longest Substring Without Repeating Characters(LeetCode)
- Leetcode 3 Longest Substring Without Repeating Characters
- 【JAVA、C++】LeetCode 003 Longest Substring Without Repeating Characters
- leetcode (3) - Longest Substring Without Repeating Characters
- LeetCode 003 Longest Substring Without Repeating Characters
- leetcode 3 Longest Substring Without Repeating Characters最长无重复子串
- 《leetCode》:Longest Substring Without Repeating Characters
- LeetCode 3 : Longest Substring Without Repeating Characters ---- 不重复的子串