給定一個(gè)字符串为牍,請(qǐng)你找出其中不含有重復(fù)字符的 最長(zhǎng)子串 的長(zhǎng)度官硝。鏈接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
如: s = "abcabcbb", 輸出: 3 , 因?yàn)闊o重復(fù)字符的最長(zhǎng)子串是 "abc"窍箍,所以其長(zhǎng)度為 3芹彬。
充分利用HashMap數(shù)據(jù)結(jié)構(gòu)棺耍,從字符串頭開始遍歷糜颠,如果當(dāng)前hashmap中無重復(fù)的字符c耕拷,則將c和對(duì)應(yīng)的下標(biāo)存入hashMap中讼昆,tmp++,當(dāng)前子串長(zhǎng)度加一骚烧,反之浸赫,遇到了重復(fù)的字符c,則將已有的HashMap歸零赃绊,tmp歸零既峡,從c首次出現(xiàn)的地方的下一個(gè)字符開始重新尋找最長(zhǎng)子串。
通過if(tmp>res) res=tmp語句碧查,不斷更新最長(zhǎng)字串的長(zhǎng)度运敢,最終獲得最長(zhǎng)長(zhǎng)度res.
import java.util.HashMap;
class Solution {
public int lengthOfLongestSubstring(String s) {
if(s.length()<=1) return s.length();//長(zhǎng)度小于等于1,無重復(fù)
int res=0,tmp=0;
HashMap<Character,Integer> hm=new HashMap<Character,Integer>();
for(int i=0;i<s.length();i++){
char c=s.charAt(i);
if(hm.containsKey(c)){
i=hm.get(c);//已經(jīng)包含c了忠售,則找到c第一次出現(xiàn)的位置
tmp=0;
hm=new HashMap();
continue;
}
hm.put(c,i);
tmp++;
if(tmp>res) res=tmp;
}
return res;
}
}