Leet Code OJ 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 a subsequence and not a substring.
翻譯
給定一個字符串,找到最長的子串的長度,這個子串不存在重復的字符。
例如:
輸入”abcabcbb”, 符合條件的子串就是”abc”, 長度為3。
輸入”bbbbb”, 符合條件的子串就是”b”, 長度為1
輸入”pwwkew”, 符合條件的子串就是”wke”, 長度為3。提示:要求必須是子串,例如”pwke” 是一個子序列但不是一個子串。
分析
遍歷一遍,記錄符合條件的長度count。如果遇到相同的字符,則從左往右remove直到移除掉那個相同的字符。
Java版代碼(時間復雜度O(n),空間復雜度O(n)):
public class Solution {public int lengthOfLongestSubstring(String s) {Map<Character, Integer> map = new HashMap<Character, Integer>();char[] charArr = s.toCharArray();int max = 0;int count = 0;for (int i = 0; i < charArr.length; i++) {Integer last = map.get(charArr[i]);if (last == null) {count++;if (count > max) {max = count;}} else {int start=i-count;for(int j=start;j<last;j++){map.remove(charArr[j]);count--;}}map.put(charArr[i], i);}return max;} }總結
以上是生活随笔為你收集整理的Leet Code OJ 3. Longest Substring Without Repeating Characters的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leet Code OJ 4. Medi
- 下一篇: Flume 1.7 源码分析(一)源码编