博主头像
7024w的自留地

觉宇宙之无穷,识盈虚之有数

Leetcode3.无重复的最长字符串

全部用jdk,很菜就是了...

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int sl = s.length();
        if (sl < 2) {
            return sl;
        }
        int minLength = 0;
        String res = String.valueOf(s.charAt(0));
        for(int right = 1;right<sl;right++){
            String b = String.valueOf(s.charAt(right));
            //如果res中不包含b字符
            int index = res.indexOf(b);
            if (index == -1) {
                res += b;
                //右指针右移
            } else {
                //如果res中包含b字符
                //计算该字符大小
                if (res.length() > minLength) {
                    minLength = res.length();
                }
                //截取从b后的所有字符串+b
                res = res.substring(index+1) + b;
            }
        }
        return Math.max(minLength, res.length());
    }
}
发表新评论