本文共 1234 字,大约阅读时间需要 4 分钟。
题目描述
请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。示例 1:
输入: “abcabcbb”
输出: 3 解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。 示例 2:输入: “bbbbb”
输出: 1 解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。 示例 3:输入: “pwwkew”
输出: 3 解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。 请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串。来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zui-chang-bu-han-zhong-fu-zi-fu-de-zi-zi-fu-chuan-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。Java
class Solution { //动态规划和模拟哈希表 public int lengthOfLongestSubstring(String s) { //用数组代替哈希表存储出现的字符上次出现的位置,初始化值为-1 if(s.length()<2) return s.length(); int position[]=new int [256]; //剑指offer书上是26个字母, 但是这里是ASCII上的256个字符 for(int i=0;icurlength) curlength++; else{ if(curlength>maxlength) maxlength=curlength; curlength=i-preIndex; } position[(int)s.charAt(i)]=i; } if(curlength>maxlength) maxlength=curlength; return maxlength; } }
//滑动窗口法
class Solution { //滑动窗口,用Set维护一个不重复的窗口 public int lengthOfLongestSubstring(String s) { int res=0; Setset=new HashSet<>(); for(int l=0,r=0;r