題目:
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,bca,cab,cb,b,其中最長3,
字符串pwwkew中子串有p,pw,w,wk,wke,kew最長為3,其中的w,是 (p,w,w),p和第一個重復的w不相連,
所以得到的不重復子串是w,像題目中說的"wke"和"pwke"一樣。
解題的思路:遍歷字符串,將字符和下標存到map中,循環判斷map是否有重復的元素,如果有則先得到map中重復元素位置為尾的字符串長度(j),再用當前循環的字符串長度減去它,得到去除重復數字的子串長度,然后比較得到最大數。如果當前循環判斷的元素不重復,就用當前循環的字符串長度減去 j,(if j=0說明,之前也沒有重復的數字)。
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的代碼我差不多。我第一次看到題的思路和一般人都是暴力循環破解,時間復雜度就不行了,然后在思考了一下,先算出差,
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的值就是算出的差,
}
其實和上面的代碼一樣。