0
点赞
收藏
分享

微信扫一扫

LeetCode-003-无重复字符的最长子串

路西法阁下 2021-09-28 阅读 45
LeetCode

无重复字符的最长子串

解法一:滑动窗口法
import java.util.ArrayList;
import java.util.List;

public class Solution {
    public static int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }

        int count = 0;
        int charAt = 0;
        List<Character> charList = new ArrayList<Character>(s.length());
        for (int i = 0; i < s.length(); i++) {
            List<Character> subList = charList.subList(charAt, i);
            if (subList.contains(s.charAt(i))) {
                charAt = charList.lastIndexOf(s.charAt(i)) + 1;
            }
            if (i + 1 - charAt > count) {
                count = i + 1 - charAt;
            }
            charList.add(s.charAt(i));
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println(lengthOfLongestSubstring("abcabcbb"));
    }
}
举报

相关推荐

0 条评论