查找一个字符串中最长的字符串,这个思路就是从左向右找,用i向右找,j标识开始统计的字符。max记录最大长度.如:
Input: "pwwkew"
Output: 3
Explanation: 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.
[1]算法如下,复杂度O(n)
import java.util.HashMap;
import java.util.Map;
class Solution {
public int lengthOfLongestSubstring(String s) {
int max = 0;
Map<Character,Integer> map= new HashMap<Character,Integer>();
for(int i =0,j=0;i < s.length();i++){
Character cha = s.charAt(i);
if(map.containsKey(cha)){
j = Math.max(j,map.get(cha)+1);
}
map.put(cha,i);
max = Math.max(max,i-j + 1);
}
return max;
}
}
、