资讯专栏INFORMATION COLUMN

leetcode 3 Longest Substring Without Repeating Cha

xcold / 2627人阅读

摘要:题目详情题目要求输入一个字符串,我们要找出其中不含重复字符的最长子字符串,返回这个最长子字符串的长度。对于字符串中的每一个字符,先判断中是否已经存在这个字符,如果不存在,直接将添加到,如果已存在,则新的字符串就从不含前一个字符的地方开始。

题目详情
Given a string, find the length of the longest substring without repeating characters.

题目要求输入一个字符串,我们要找出其中不含重复字符的最长子字符串,返回这个最长子字符串的长度。

Examples:
输入"abcabcbb",最长不含重复字符子字符串"abc",返回3.
输入"bbbbb",最长不含重复字符子字符串"b",返回1.
输入"pwwkew",最长不含重复字符子字符串"wke",返回3.

想法

这道题的思路也比较简单,首先声明一个max变量存储结果,声明一个temp字符串暂存当前的不重复字符串。

对于字符串中的每一个字符c,先判断temp中是否已经存在这个字符,如果不存在,直接将c添加到temp,如果已存在,则新的temp字符串就从不含前一个c字符的地方开始。

每次截取字符串之前都判断一下长度是否比max大。

解法
    public int lengthOfLongestSubstring(String s) {
        int max = 0;
        String temp = "";
        
        for(char c : s.toCharArray()){
            int index = temp.indexOf(c);
            if(index < 0) temp += c;
            else{
                max = (temp.length() > max) ? temp.length() : max ;
                temp = temp.substring(index+1);
                temp += c;
            }
        }
        max = (temp.length() > max) ? temp.length() : max;
        return max;
    }

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/68557.html

相关文章

  • [Leetcode] Longest Substring Without Repeating Cha

    摘要:哈希表是最自然的想法。在遍历字符串时,我们先根据哈希表找出该字符上次出现的位置,如果大于等于子字符串首,便更新子字符串首。结束后,将该字符新的位置放入哈希表中。 Longest Substring Without Repeating Characters 最新更新解法:https://yanjia.me/zh/2018/12/... Given a string, find the ...

    FleyX 评论0 收藏0
  • [LeetCode] Longest Substring Without Repeating Cha

    摘要:建立数组,存储个字符最近一次出现的位置。首次出现某字符时,其位置标记为,并用无重复字符计数器记录无重复字符的长度,再在更新其最大值。循环完整个字符串后,返回最大值。 Problem Given a string, find the length of the longest substring without repeating characters. Examples: Given ...

    CoderStudy 评论0 收藏0
  • [LeetCode] Longest Substring Without Repeating Cha

    Problem 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...

    graf 评论0 收藏0
  • [LintCode] Longest Substring Without Repeating Cha

    摘要:哈希表法双指针法只有当也就是时上面的循环才会结束,,跳过这个之前的重复字符再将置为 Problem Given a string, find the length of the longest substring without repeating characters. Example For example, the longest substring without repeat...

    Scliang 评论0 收藏0
  • [Leetcode]Longest Substring Without Repeating Char

    摘要:解题思路本题借助实现。如果字符未出现过,则字符,如果字符出现过,则维护上次出现的遍历的起始点。注意点每次都要更新字符的位置最后返回时,一定要考虑到从到字符串末尾都没有遇到重复字符的情况,所欲需要比较下和的大小。 Longest Substring Without Repeating CharactersGiven a string, find the length of the lon...

    awesome23 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<