代码拉取完成,页面将自动刷新
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;
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。