題目:
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.
題目大意呢就是去除重復(fù)的數(shù)字佑颇,找到最長的子串,返回長度草娜。
例如題目中給出的abcabcbb挑胸,的子串有abc,bca,cab,cb,b,其中最長3,
字符串pwwkew中子串有p,pw,w,wk,wke,kew最長為3宰闰,其中的w,是 (p,w,w)茬贵,p和第一個重復(fù)的w不相連,
所以得到的不重復(fù)子串是w移袍,像題目中說的"wke"和"pwke"一樣解藻。
解題的思路:遍歷字符串,將字符和下標存到map中葡盗,循環(huán)判斷map是否有重復(fù)的元素螟左,如果有則先得到map中重復(fù)元素位置為尾的字符串長度(j),再用當前循環(huán)的字符串長度減去它,得到去除重復(fù)數(shù)字的子串長度胶背,然后比較得到最大數(shù)虫啥。如果當前循環(huán)判斷的元素不重復(fù),就用當前循環(huán)的字符串長度減去 j,(if j=0說明奄妨,之前也沒有重復(fù)的數(shù)字)。
java代碼如下:
import java.util.HashMap;
import java.util.Map;
/**
* Created by Wangjianxin on 2017/7/6 0006.
*/
public class LongestSubstring {
public static void main(String[] args) {
String s = "qwwkew";
System.out.println(lengthOfLongestSubstring(s));
}
public static int lengthOfLongestSubstring(String s) {
Map<Character,Integer> map = new HashMap<Character,Integer>();
final int len = s.length();
if(s.length() == 1 || s.length() == 0){
return s.length();
}
int max = 0;
int j = 0;
for(int i =0;i<len;i++){
if(map.containsKey(s.charAt(i))){
int mapi = map.get(s.charAt(i)) + 1;
j = Math.max(j,mapi);
}
max = Math.max(max,i-j+1);
map.put(s.charAt(i),i);
}
return max;
}
}
看了下leetcode的solution的代碼我差不多苹祟。我第一次看到題的思路和一般人都是暴力循環(huán)破解砸抛,時間復(fù)雜度就不行了,然后在思考了一下树枫,先算出差直焙,
if(map.containsKey(s.charAt(i))){
int mapi = map.get(s.charAt(i)) + 1;
String mapis = s.substring(0,mapi);
String is = s.substring(0,i+1);
int diflen = is.length() - mapis .length();
//這個 diflen的值就是算出的差,
}
其實和上面的代碼一樣砂轻。