繁体   English   中英

最长 Substring 无重复字符:错误答案

[英]Longest Substring Without Repeating Characters: Wrong answer

我花了几个小时试图找出该方法为这个特定测试用例返回错误答案的原因:“qrsvbspk”。 该方法返回 6 而不是 5。我不知道哪里出了问题。 请帮助!

这是我的方法:

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int i = 0;
        int max_count = -1;
        int count = 0;
        
          if(s.length() == 0)
              return 0;
        
        HashSet<Character> set = new HashSet();
        
        int k = 0;
        while(k < s.length()){
            i = k;
            while(i < s.length() && !set.contains(s.charAt(i))){
                count++;
                set.add(s.charAt(i++));
            }
            if(count >= max_count){
                max_count = count;
                set.clear();
                count = 0;
            } 
                k++;
        }
        return max_count;
    }
}

您的方法是不正确的,因为如果找到更长的 substring,您应该只清除Set并重置count ,而您应该在外循环的每次迭代中执行此操作。

您可以使用两点法来提高效率。 当左指针从0移动到小于String长度的 1 时,我们不断增加右指针,直到到达Set中已经存在的字符。 之后,当前 substring 的长度是right - left的,我们从Set中删除左侧索引处的字符。 由于两个指针最多可以增加N次(其中NString的长度),因此这种方法在O(N)中运行。

public int lengthOfLongestSubstring(String s) {
    int max_count = 0;
    HashSet<Character> set = new HashSet();
    int left = 0, right = 0;
    while(left < s.length()){
        while(right < s.length() && set.add(s.charAt(right))){
            ++right;
        }
        max_count = Math.max(max_count, right - left);
        set.remove(s.charAt(left++));
    }
    return max_count;
}

我花了几个小时试图找出该方法为这个特定的测试用例返回错误答案的原因:“qrsvbspk”。 该方法返回 6 而不是 5。我不知道出了什么问题。 请帮忙!

这是我的方法:

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int i = 0;
        int max_count = -1;
        int count = 0;
        
          if(s.length() == 0)
              return 0;
        
        HashSet<Character> set = new HashSet();
        
        int k = 0;
        while(k < s.length()){
            i = k;
            while(i < s.length() && !set.contains(s.charAt(i))){
                count++;
                set.add(s.charAt(i++));
            }
            if(count >= max_count){
                max_count = count;
                set.clear();
                count = 0;
            } 
                k++;
        }
        return max_count;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM