package leetcode; import java.util.HashMap; import java.util.Map; /** * 3. 无重复字符的最长子串 * 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。 * <p> * 示例 1: * <p> * 输入: "abcabcbb" * 输出: 3 * 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。 * 示例 2: * <p> * 输入: "bbbbb" * 输出: 1 * 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。 * 示例 3: * <p> * 输入: "pwwkew" * 输出: 3 * 解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。 * 请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。 */ public class lengthOfLongestSubstring { public static void main(String[] args) { String text = "abcabcbb"; System.out.println(lengthOfLongestSubstring(text)); } public static int lengthOfLongestSubstring(String s) { int n = s.length(), ans = 0; Map<Character, Integer> map = new HashMap<>(); // current index of character // try to extend the range [i, j] for (int j = 0, i = 0; j < n; j++) { //如果map中包含了已经存在的字符。则开始计算起始值i的值 if (map.containsKey(s.charAt(j))) { i = Math.max(map.get(s.charAt(j)), i); } //每次循环计算区域长度和本次比较的大小并且赋值 ans = Math.max(ans, j - i + 1); //添加map中每个字符存在的位置。 map.put(s.charAt(j), j + 1); } return ans; } }
05-17
2万+
04-07