3. Longest Substring Without Repeating Characters【leetcode】java,演算法,Substring實現,子串,HashMap

來源:互聯網
上載者:User

標籤:標記   without   sub   hashmap   bcb   seq   which   ash   contains   

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”是子串。

實現方式:

1.擷取字串長度
2.紀錄當前值為左標記
3.判斷當前字母是否出現過,若出現過就更新當前位置為新的左標記
4.如果當前 值比res大則更新res長度

方法:使用HashMap這樣,遇到重複就跳過迴圈,節約時間和空間

 1 public class Solution { 2     public int lengthOfLongestSubstring(String s) { 3         Map<Character,Integer> map =new HashMap<>(); 4         int res =0,len=s.length(); 5         for(int i=0,j=0;j<len;j++){ 6             if(map.containsKey(s.charAt(j))){ 7                 i=Math.max(map.get(s.charAt(j)),i); 8             } 9             map.put(s.charAt(j),j+1);10             res =Math.max(j-i+1,res) ;11         }12         return res;13     }14 }

 

3. Longest Substring Without Repeating Characters【leetcode】java,演算法,Substring實現,子串,HashMap

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.