【问题标题】:I'm getting an error for my c++ code when my input string contains spaces [closed]当我的输入字符串包含空格时,我的 c++ 代码出现错误[关闭]
【发布时间】:2021-05-04 09:38:33
【问题描述】:

问题链接:https://leetcode.com/problems/longest-substring-without-repeating-characters/

class Solution {
public:
    int lengthOfLongestSubstring(string s) 
    {
     
     if(s.length()==0)
         return 0;
        
     if(s.length()==1)
         return 1;
     
     int ans=0;
     int len=0;
     //s.erase(remove(s.begin(), s.end(), ' '), s.end());
     vector<int> count(257,0);
     vector<int> last_index(257,0);
        
     for(int i=0;i<s.length();i++)
     {
         if(count[s[i]-'0']==0)
         {  
            count[s[i]-'0']++;
            last_index[s[i]-'0']=i; //storing the index of the character
            len++;
            ans=max(ans,len);
         }
         else if(count[s[i]-'0']>=1)
         {
             fill(count.begin(), count.begin()+last_index[s[i]-'0'], 0); // reducing the count to 0 till the last position of the matched character
             len=i-last_index[s[i]-'0']; //calculating the new length of the string
             count[s[i]-'0']++;
             last_index[s[i]-'0']=i; //storing the latest index of the character
         }         
     }
        return ans;
    }
};

当字符串包含空格时,上述代码出现以下错误。

测试用例: "ab cabcbb"

"bbbbb"

"pwwkew"

""

" "

第 1034 行:字符 34:运行时错误:将无符号偏移量添加到 0x619000000080 溢出到 0x619000000040 (stl_vector.h) 摘要:UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu /9/../../../../include/c++/9/bits/stl_vector.h:1043:34

【问题讨论】:

  • 请提供minimal reproducible example,这是一个可以编译的单个文件。作为这里的新用户,也可以使用tour 并阅读How to Ask
  • 测试用例:“ab cabcbb”“bbbbb”“pwwkew”“”“”
  • 如果您想扩展您的问题,只需edit。此外,当您使用它时,请使格式保持一致。
  • 我在问题正文中添加了...抱歉将其放在评论部分

标签: c++ string stl


【解决方案1】:
for(int i=0;i<s.length();i++)
     {
         if(count[s[i]-'0']==0)
         {

' ' (0x20) 的值小于'0' (0x30) 的值,因此s[i]- '0' 是包含空格字符的s[i] 的负值。将此值转换为size_t(用于索引的类型)会产生一个非常接近最大值的值,该值超出了vector 的范围。

【讨论】:

  • 非常感谢您提供这些宝贵的信息......那么在这种情况下我应该如何处理......或者我应该寻找另一种方法
  • @AbhinavAashish 我还没有完成你所有的算法,但似乎添加最小可能的字符值应该允许你从可能的字符范围转换到[0, 255] 的范围。或者,您可以通过对unsigned char 进行强制转换来实现相同的目的。我认为这是您在向量中获取索引的目的?顺便说一句,你为什么要删除一系列计数?
  • @AbhinavAashish 您也可能对我的回答感兴趣:stackoverflow.com/a/65858154/2991525 我认为您的方法的不同之处在于您尝试使用vector 而不是unordered_map跨度>
猜你喜欢
  • 2021-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-13
  • 1970-01-01
  • 2018-07-15
  • 2021-03-01
  • 2022-01-15
相关资源
最近更新 更多