LeetCode —— 无重复字符的最长子串

版权声明: https://blog.csdn.net/qq_36786991/article/details/86755782

给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

示例 1:

输入: "abcabcbb"
输出: 3 
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。

示例 2:

输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。

示例 3:

输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
     请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。

注意点:

  • 滑动滑块到最后一个时,记得记录最后一个数
  • 还可以优化,用集合API省去部分代码
  • 考虑没有滑动的情况
package 无重复字符的最长子串;

import java.util.*;

/**
 * @Auther: 简单DI年华
 * @Date: 19-2-3 00:05
 */
class Solution {
    public static int lengthOfLongestSubstring(String s) {
        List<Character> list = new ArrayList();
        List<Integer> count = new ArrayList<>();

        for (int i = 0; i < s.length(); i++) {
            Character c = s.charAt(i);
            if(list.size()>0){

                boolean flag = true;
                for (int j = 0; j < list.size(); j++) {
                    if(list.get(j).equals(c)){
                        count.add(list.size());
                        for (int k = 0; k <= j; k++) {
                            list.remove(0);
                        }
                        list.add(c);
                        flag = false;
                        break;
                    }
                }

                if(flag == true){
                    list.add(c);
                }

                if(i == s.length()-1){
                    count.add(list.size());
                }


            }else{
                list.add(c);
            }
        }

        if(count.size() == 0){
            return s.length();
        }
        Collections.sort(count);
        return count.get(count.size()-1);
    }



    public static void main(String[] args) {
        int a = Solution.lengthOfLongestSubstring("aab");
        System.out.println(a);
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_36786991/article/details/86755782