2 Star 10 Fork 2

CG国斌 / myleetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
_3.java 1.33 KB
一键复制 编辑 原始数据 按行查看 历史
package com.hit.basmath.learn.hash_table;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* 3. Longest Substring Without Repeating Characters
* <p>
* Given a string, find the length of the longest substring without repeating characters.
* <p>
* Example 1:
* <p>
* Input: "abcabcbb"
* Output: 3
* Explanation: The answer is "abc", with the length of 3.
* <p>
* Example 2:
* <p>
* Input: "bbbbb"
* Output: 1
* Explanation: The answer is "b", with the length of 1.
* <p>
* Example 3:
* <p>
* Input: "pwwkew"
* Output: 3
* Explanation: The answer is "wke", with the length of 3.
* <p>
* Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
*/
public class _3 {
/**
* Slide window method of optimize
*
* @param s target string
* @return size
*/
public int lengthOfLongestSubstring(String s) {
int n = s.length(), ans = 0;
Map<Character, Integer> map = new HashMap<>();
for (int end = 0, start = 0; end < n; end++) {
char alpha = s.charAt(end);
if (map.containsKey(alpha)) {
start = Math.max(map.get(alpha), start);
}
ans = Math.max(ans, end - start + 1);
map.put(s.charAt(end), end + 1);
}
return ans;
}
}
Java
1
https://gitee.com/guobinhit/myleetcode.git
git@gitee.com:guobinhit/myleetcode.git
guobinhit
myleetcode
myleetcode
master

搜索帮助