c++ - IF 语句给出错误答案,而 ELSE IF 工作正常
问题描述
我正在解决GeekForGeeks上的 Anagrams 出现次数问题。
int search(string ana, string s) {
unordered_map<char, int> m;
for(auto it : ana) m[it]++;
int k=ana.length();
int count=m.size();
int i=0, j=0;
int ans=0;
while(j<s.length()){
if(m.find(s[j])!=m.end()){
m[s[j]]--;
if(m[s[j]]==0) count--;
}
if(j-i+1<k) j++;
if(j-i+1==k){ //**else if works**
if(count==0) ans++;
if(m.find(s[i])!=m.end()){
m[s[i]]++;
if(m[s[i]]==1) count++;
}
i++;
j++;
}
}
return ans;
}
此代码在使用时有效else if(j-i+1==k)
,但在简单使用时if(j-i+1==k)
给出错误答案。
对于测试用例:
s = forxxorfxdofr
ana = for
Output: 3
但是当只使用if
它时
Output :0
解决方案
不同的是,在这个 if 语句之后
if(j-i+1<k) j++;
变量 j 递增,下一个 if 语句
if(j-i+1==k){ /
在任何情况下都可以控制并且可以评估为真。
如果使用 if else 语句
if(j-i+1<k) j++;
else if(j-i+1==k){ /
那么如果第一个 if 语句被评估,则 else if 语句将被跳过。
所以从逻辑上讲,这两个代码片段的行为是不同的。
这是一个简化的演示程序。
#include <iostream>
int main()
{
int x = 0;
if ( x == 0 ) ++x;
if ( x == 1 ) ++x;
std::cout << "x = " << x << '\n';
x = 0;
if ( x == 0 ) ++x;
else if ( x == 1 ) ++x;
std::cout << "x = " << x << '\n';
return 0;
}
程序输出为
x = 2
x = 1
调查一下。
推荐阅读
- python - 不可能在 QTextBrowser 中显示作者、记录者、翻译者
- python - 使用 python 从盈透证券获取买卖价
- google-apps-script - UrlFetchApp.fetch 由 Sheets 事件触发,因缺少权限而失败,但在直接运行时有效
- xml - 使用 XSLT 根据属性修改数据
- php - 作曲家更新给出错误说插件无法初始化,没有为每个包找到类
- ios - SwiftUI SecureField 跟踪活动/非活动状态
- python - 如何添加脚本任务以在 Bamboo 中运行 pytest
- android - 如何从android中的“MainActivity”更新片段内的Listview?
- python - Python Selenium - 在未找到预期值时尝试使测试失败
- python - 如何使用函数显示对象的属性值