当我的输入字符串包含空格时,我的 C++ 代码出现错误
I'm getting an error for my c++ code when my input string contains spaces
问题Link: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:未定义行为 /usr/bin/../lib/gcc/x86_64-linux-gnu/9 /../../../../include/c++/9/bits/stl_vector.h:1043:34
for(int i=0;i<s.length();i++)
{
if(count[s[i]-'0']==0)
{
' '
(0x20
)的值小于'0'
(0x30
)的值,所以s[i]- '0'
为负值s[i]
包含一个 space 字符。将该值转换为 size_t
(用于索引的类型)会产生一个非常接近最大值的值,该值超出了 vector
.
的范围
问题Link: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:未定义行为 /usr/bin/../lib/gcc/x86_64-linux-gnu/9 /../../../../include/c++/9/bits/stl_vector.h:1043:34
for(int i=0;i<s.length();i++)
{
if(count[s[i]-'0']==0)
{
' '
(0x20
)的值小于'0'
(0x30
)的值,所以s[i]- '0'
为负值s[i]
包含一个 space 字符。将该值转换为 size_t
(用于索引的类型)会产生一个非常接近最大值的值,该值超出了 vector
.