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

    思路 大家都把这题的思路看作一个两头可以滑动的窗口,具体做法就是用两个数记录当前子串的首尾位置,先固定头部,不断延...

  • leetcode3

    Longest Substring Without Repeating Characters Given a st...

  • Leetcode3

    题目描述: 判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。 示例 1: ...

  • leetcode3

    给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。示例 1:输入: s = "abcabcbb...

  • 【leetcode3】 3. Longest Substrin

    关键字:最长不重复子串、双指针 难度:Medium 题目大意:求一个字符串最长不重复子串的长度 题目: Given...

  • leetCode3最大无重复字符的子串

    最长无重复字符的子串 给定一个字符串,找出不含有重复字符的最长子串的长度。 示例: 实现思路 初始化hashSet...

  • LeetCode3 无重复字符的最长子串

    这里主要是用到一个移动窗口的概念。窗口移动要解决的问题则是如果当前的字符已经重复了。那么接下来我的窗口的起始位置应...

  • LeetCode3(无重复字符的最长子串)

    题目: 解题思路 采用滑动窗口的方法来解决。从第一个字符开始循环,并把字符放到map中,如果 s[j]在 [i, ...

  • leetcode3 无重复字符的最长子串

    给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。 示例 1: 输入: "abcabcbb"输出: ...

  • leetcode3 无重复字符的最长子串

    题目 无重复字符的最长子串 分析 典型的滑动窗口题目。 一个窗口用两个指针left,right来维护,不断移动ri...

网友评论

      本文标题:leetcode3

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