Longest Substring Without Repeating Characters,优化版
/**
*
* Given a string, find the length of the longest substring without repeating characters.<br>
* Examples:<br>
* Given "abcabcbb", the answer is "abc", which the length is 3.<br>
* Given "bbbbb", the answer is "b", with the length of 1.<br>
* 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.<br>
*
* @author yangxf
*
*/
class Solution {
public int lengthOfLongestSubstring(String s) {
int ret = 0;
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (int j = 0, i = 0; j < s.length(); j++) {
if (map.containsKey(s.charAt(j))) {
i = Math.max(map.get(s.charAt(j)), i);
}
ret = Math.max(ret, j - i + 1);
map.put(s.charAt(j), j + 1);
}
return ret;
}
}
之前完成的ARTS中算法部分的Longest Substring Without Repeating Characters,发现执行效率很低,看了网站提供的解决方案,感觉还是有所启发和提升。
暂无
暂无