import java.util.HashMap;
/**
* @Author:Sumschol
* @date: Created in 21:17 22/01/25
* @Descriptions:
* 给定一个字符串 s ,请你找出其中不含有重复字符的最长子串的长度。
*
*
*
* 示例1:
*
* 输入: s = "abcabcbb"
* 输出: 3
* 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
* 示例 2:
*
* 输入: s = "bbbbb"
* 输出: 1
* 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
* 示例 3:
*
* 输入: s = "pwwkew"
* 输出: 3
* 解释: 因为无重复字符的最长子串是"wke",所以其长度为 3。
* 请注意,你的答案必须是 子串 的长度,"pwke"是一个子序列,不是子串。
* 示例 4:
*
* 输入: s = ""
* 输出: 0
*
*
* @thinking:
* 移动窗口
*
*/
public class Offer001 {
public static void main(String[] args) {
String s = "abba";
System.out.println(lengthOfLongestSubstring(s));
}
public static int lengthOfLongestSubstring(String s){
if(s.isEmpty()) return 0;
HashMap<Character, Integer> HashMap = new HashMap<>(); //K为字符 V为该字符对应的下标
int max = 0;
int len = s.length();
for(int start = 0, end = 0;end < len; end++ ){
char chr = s.charAt(end); //取出窗口末尾的字符
if(HashMap.containsKey(chr)){ //存在重复字符
//将窗口移到第一次出现此字符之后 如果此时窗口开始位置已经在第一次出现的右边 则窗口不动("abba")
start = Math.max(HashMap.get(chr) + 1, start);
}
max = Math.max(max, end - start + 1);
HashMap.put(chr, end);
}
return max;
}
}
[LeedCode]无重复字符的最长子串
最新推荐文章于 2024-07-02 23:18:46 发布