题目链接
https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
描述
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例
示例1
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例2
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例3
输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
代码
这个题目有很多种写法,但是其实差不了多少,我用滑动窗口的思想写的
class Solution {
public int lengthOfLongestSubstring(String s) {
int[] arr = new int[128];
Arrays.fill(arr, -1);
int left = -1;
int right = 0;
int res = 0;
while (right < s.length()) {
int num = (int)s.charAt(right);
left = Math.max(arr[num], left);
res = Math.max(res, right - left);
arr[num] = right++;
}
return res;
}
}