【LeetCode从零单排】No 3 Longest Substring Without Repeating Characters
生活随笔
收集整理的這篇文章主要介紹了
【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;}}代碼下載:https://github.com/jimenbian/GarvinLeetCode
/********************************
* 本文來自博客 ?“李博Garvin“
* 轉載請標明出處:http://blog.csdn.net/buptgshengod
******************************************/
總結
以上是生活随笔為你收集整理的【LeetCode从零单排】No 3 Longest Substring Without Repeating Characters的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【LeetCode从零单排】No 114
- 下一篇: 苹果系统修复若干办法