题目:
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的值就是算出的差,
}
其实和上面的代码一样。