【LeetCode從零單排】No 3 Longest Substring Without Repeating Characters
題目
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
這道題看似簡單,但是用遍歷方法的話非常麻煩。下面這種用hashmap處理方法,是在discuss裡看到的,很巧妙。
程式碼
public class Solution {
public int lengthOfLongestSubstring(String s) {
if(s.length()==0) return 0;
HashMap<Character,Integer> map=new HashMap<Character,Integer>();
int max=0;
for(int i=0,j=0;i<s.length();i++){
if(map.containsKey(s.charAt(i))){
j = Math.max(j,map.get(s.charAt(i))+1);
}
map.put(s.charAt(i),i);
max = Math.max(max,i-j+1);
}
return max;
}
}
/********************************
* 本文來自部落格 “李博Garvin“
* 轉載請標明出處:http://blog.csdn.net/buptgshengod
******************************************/
相關文章
- Leetcode 3 Longest Substring Without Repeating CharactersLeetCode
- Leetcode 3. Longest Substring Without Repeating CharactersLeetCode
- Leetcode javascript 3 longest-substring-without-repeating-charactersLeetCodeJavaScript
- #3 Longest Substring Without Repeating Characters[M]
- [LeetCode] 3. Longest Substring Without Repeating Characters 題解LeetCode
- LeetCode Longest Substring Without Repeating Characters(003)解法總結LeetCode
- LeetCode3:Longest Substring Without Repeating Characters(無重複字元的最長子串)LeetCode字元
- Leet Code 3. Longest Substring Without Repeating Characters (最長的沒有重複字元的子字串)字元字串
- 【Leetcode】3. Longest Substring Without RepeatingCharacters無重最長子串LeetCodeGC
- LeetCode 5 (Longest Palindromic Substring)LeetCode
- [LeetCode] 2414. Length of the Longest Alphabetical Continuous SubstringLeetCodeAlphabet
- [leetcode] 1624. Largest Substring Between Two Equal CharactersLeetCode
- Leetcode5: Longest Palindromic Substring(最長迴文子串)LeetCode
- 【3y】從零單排學Redis【青銅】Redis
- Mysql從零單排-1MySql
- 從零單排學Redis【黃金】Redis
- 從零單排學Redis【白銀】Redis
- 從零單排學Redis【鉑金一】Redis
- 從零單排學Redis【鉑金二】Redis
- SPOJ 1811 Longest Common Substring(字尾自動機)
- SpringBoot從零單排 ------初級入門篇Spring Boot
- 從零開始實現簡單 RPC 框架 3:配置匯流排 URLRPC框架
- 從零單排Java 8(3) —— List結合Lambdas對排序的高階用法Java排序
- Leetcode 32 Longest Valid ParenthesesLeetCode
- Leetcode 14 Longest Common PrefixLeetCode
- LeetCode之Find Common Characters(Kotlin)LeetCodeKotlin
- [LeetCode] 451. Sort Characters By FrequencyLeetCode
- 「從零單排canal 03」 canal原始碼分析大綱原始碼
- 「從零單排canal 05」 server模組原始碼解析Server原始碼
- 「從零單排canal 07」 parser模組原始碼解析原始碼
- 從零單排,使用 Netty 構建 IM 聊天室~Netty
- 「從零單排canal 06」 instance模組原始碼解析原始碼
- Laravel 從零單排系列教程 01 :Homestead 環境搭建Laravel
- [LeetCode] 32. Longest Valid ParenthesesLeetCode
- [LeetCode] 5. Longest Palindromic SLeetCode
- 【Leetcode】1081. Smallest Subsequence of Distinct CharactersLeetCode
- Leetcode 30 Substring with Concatenation of All WordsLeetCode
- 三分鐘從零單排js靜態檢查JS
- Spring AOP從零單排-織入時期原始碼分析Spring原始碼