首页 > 解决方案 > 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 

标签: c++if-statement

解决方案


不同的是,在这个 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

调查一下。


推荐阅读