leetcode3

作者: 小烈yhl | 来源:发表于2018-12-04 13:11 被阅读0次
    1. Longest Substring Without Repeating Characters

    Given a string, find the length of the longest substring without repeating characters.

    Example 1:

    Input: "abcabcbb"
    Output: 3
    Explanation: The answer is "abc", with the length of 3.
    Example 2:

    Input: "bbbbb"
    Output: 1
    Explanation: The answer is "b", with the length of 1.
    Example 3:

    Input: "pwwkew"
    Output: 3
    Explanation: 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.

    我的思路:
    1、将所有的字符串依此放入ArrayList
    2、每次放入前,先比较,此时输入的字符是否在之前出现再Arraylist中
    3、如果出现过,先把长度记录下来,然后在数组表中删除此字符之前的所有字符(包含这个字符)
    4、然后再添加这个字符,再放入之后的字符进行比较,如此循环
    5、值得注意的是最后一次循环,如果没有重复字符的话,是不会记录最后一个字符串长度的,所以需要我们最后循环结束后,duo'jia

    public class leet3 {
         public int lengthOfLongestSubstring(String s) {
             int count=0;
             
             ArrayList<Character> store = new ArrayList<Character>();
             for(int i=0; i<s.length();i++) 
             {
                 if(store.contains(s.charAt(i))) {
                     if(store.size()>count) count = store.size();//计算大小,也就是字符串长度
                     int c = store.indexOf(s.charAt(i));//计算此重复的字符出现在数组表里的索引,然后删除索引之前的所有
                     for(int j = c ; j >=0 ; j--)
                     store.remove(j);
                     store.add(s.charAt(i));//最后得把重复的那个字符,加在文末
                 }
                 else store.add(s.charAt(i));
            }
             if (store.size()>count) //!最后的放进去的元素,如果没有重复是不会进前面if语句内进行count和size的比较的,所以在最后补一次比较,不然如果最后的字符串是最长的话,我们就没有把它记录进去
                 count = store.size();
                
             return count;
            
             }
         
         public static void main(String[] args) {
             String s = "asoidnaofbasudoansdkasndaskn";
             leet3 exp = new leet3();
             int res = exp.lengthOfLongestSubstring(s);
             System.out.println(res);
             
         }
            
                
            }
    

    相关文章

      网友评论

          本文标题:leetcode3

          本文链接:https://www.haomeiwen.com/subject/uaemcqtx.html