leetcode3

  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);
         
     }
        
            
        }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,126评论 0 10
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 13,140评论 0 13
  • 目录 上一章:杀与被杀徘徊(五) 第四十章:杀与被杀徘徊(六) 狂奔的韩信感知到迎面而来的强大箭矢,他自信能挡下它...
    灵夜狼阅读 3,471评论 36 9
  • 2018.1.13,正式上完《哈佛幸福课》,打卡。 2017年,因为失恋,因为离职,我经历了我目前人生中最抑郁的一...
    lynlynlee阅读 3,355评论 0 2
  • 1.你之前有了解过么? 了解了哪些呢? 你最想关注的是哪方面? 你目前在职么? 2.宝宝多大? 目前吃的是哪款? ...
    summer洋葱OMALL阅读 994评论 0 0