leetcode第3题 最长无重复子字符串

2019-06-12  本文已影响0人  CoderAPang

@(LeetCode)[字符串]
leetcode 3 Longest Substring Without Repeating Characters

题目描述:Given a string, find the length of the longest substring without repeating characters.
总结:考察String的一些基本语法
1.String.length():获取String的长度</br>
2.String.charAt(i):从String中查找字符i第一次出现的下标,查不到则为-1</br>

方案:滑动窗口算法

class Solution {
    public int lengthOfLongestSubstring(String s) {
         int LongestLength = 0;
        String noRepeatString = "";
        for(int i=0;i<s.length();i++){
                if(noRepeatString.indexOf(s.charAt(i))!=-1){//有这个字符
                    if(noRepeatString.length()>LongestLength){
                        LongestLength=noRepeatString.length();
                    }
                    if(noRepeatString.indexOf(s.charAt(i))+1<noRepeatString.length()){
                      noRepeatString=noRepeatString.substring(noRepeatString.indexOf(s.charAt(i))+1,noRepeatString.length());
                    }else {
                        noRepeatString="";
                    }
                }
            noRepeatString+=s.charAt(i);
            
        }
        
        if(noRepeatString.length()>LongestLength){
                        LongestLength=noRepeatString.length();
        }
        return LongestLength;
    }
}
上一篇下一篇

猜你喜欢

热点阅读