当前位置 博文首页 > __李少的博客:leetcode第3个算法题目

    __李少的博客:leetcode第3个算法题目

    作者:[db:作者] 时间:2021-08-15 13:36

    这是leetcode第3个算法题目,当时看到这个题目,心里就有思路了,感觉很简单,大概就是把每一个没有重复的字符串拿出来,比一比哪个最长,对了,题目如下。
    Given a string, find the length of the longest substring without repeating characters.
    Examples:

    Given “abcabcbb”, the answer is “abc”, which the length is 3.

    Given “bbbbb”, the answer is “b”, with the length of 1.

    Given “pwwkew”, the answer is “wke”, with the length of 3. Note that the answer must be a substring, “pwke” is a subsequence and not a substring.
    心里很开心啊,愉快的写代码,代码如下:

    public static int my(String str)`{`
            int res = 0;
            for(int i = 0;i<str.length();i++){
                String a = "";
                for(int j = i+1;j<=str.length();j++){
                    a = str.substring(i,j);
                    if(is(a)){
                        continue;
                    }else{
                        a = str.substring(i,j-1);
                        break;  
                    }           
                }
                res = a.length()>res?a.length():res;
            }
            return res;
        }
    public static  boolean is(String str){
              System.out.println("str = "+str);
              List list = new ArrayList();
              for(int i = 0 ;i<str.length();i++){
                    if (list.contains(str.charAt(i))){
                       return false;
                     }else{
                       list.add(str.charAt(i));
                     }
                }
                   return true;
          }

    这代码没毛病,可以算出来正确结果,可惜告诉我超时,我一看,已经到达n的四次方的复杂度了,确实一开始没有往效率方面思考。好吧,一切推倒重来。
    新的代码如下:

    public static int find(String a,char r){
            for(int i = 0;i<a.length();i++){
                if(a.charAt(i)==(r)){
                    return i;
                }
            }
            return -1;
        }
        public static int my2(String str){
            int i = 0;
            String res = "";
            int m = 0;
            while(i<str.length()){
                char r = str.charAt(i);
                if(find(res,r)!=-1){        
                    m = res.length()>m?res.length():m;
                    int x = find(res,r)+1;
                    res = res.substring(x)+r;
                }else{
                    res = res+r;
                    m = res.length()>m?res.length():m;
                }
                i++;
            }
            return m;
        }

    这个算法好像只有n方复杂度,完全没问题。可以得出正确结果。思路的话,就是拿出逐个字符对字符串进行遍历,当拿出的这个字符,与res字符串重复了,那么久找出那个重复的元素,从此元素之后再取字符串为res。算法不难,应该可以看懂代码,我描述不清楚,有问题可以交流。

    cs