• HDU 5284 wyh2000 and a string problem(错误总结)


    题目链接:戳我(英文)戳我(中文)

    题目大意:

    看中文

    样例解释:

    解题思路:

    for循环跑一遍,遇到 vv 就变成 w 就行了

    错误的代码

    int k = 0, i;
        for(i = 0; str[i+1]; i++)
        {
            printf("%d %c
    ", i, str[i]);
            if(str[i] == 'v' && str[i+1] == 'v')
            {
                i = i + 1; //这里不能加1
                str[i] = 'w';
                //k++;
            }
    
            if(str[i] == tar[k])
            {
                k++;
            }
            printf("i = %d
    ", i);
            if(k == 3) return true;
        }
        for(; str[i]; i++)
        {
            if(str[i] == tar[k]) k++;
            if(k == 3) return true;
        }
    

    因为scanf在读入字符串的时候,如果上次字符串较长,不会将长的那部分全部清空,所以在 for 循环的时候,假设上一次的字符串是 "aaaawyh",那么这次输入的字符串是"vv",其实是”vvawyh", 故 在代码的第7行,又一次加了1,会跳过 '',从而导致继续向后读,所以就输出了 "Yes", 导致错误

    AC代码:

    #include <cstdio>
    #include <cstdlib>
    #include <cstring>
    #include <cctype>
    #include <cmath>
    #include <algorithm>
    #include <vector>
    #include <queue>
    #include <stack>
    #include <map>
    #define clc(a, b) memset(a, b, sizeof(a))
    using namespace std;
    
    const int inf = 0x3f;
    const int INF = 0x3f3f3f3f;
    const int maxn = 3145728+5;
    char str[maxn], tar[4] = "wyh";
    bool judge()
    {
        int k = 0, i;
        for(i = 0; str[i+1]; i++)
        {
            //printf("%d %c
    ", i, str[i]);
            if(str[i] == 'v' && str[i+1] == 'v')
            {
                //i = i + 1; //这里不能加1
                str[i] = 'w';
            }
    
            if(str[i] == tar[k])
            {
                k++;
            }
            //printf("i = %d
    ", i);
            if(k == 3) return true;
        }
        for(; str[i]; i++)
        {
            if(str[i] == tar[k]) k++;
            if(k == 3) return true;
        }
        return false;
    }
    int main()
    {
        int n;
        scanf("%d", &n);
    
    
        while(n--)
        {
            scanf("%s", str);
            if(judge())
                printf("Yes
    ");
            else
                printf("No
    ");
        }
        return 0;
    }
    

      

  • 相关阅读:
    5G和物联网:面临各种安全挑战的新兴技术
    嵌入式Linux系统的几大组件!
    物联网应用开发如何平衡用户体验与隐私安全?
    我们需要什么数据架构?
    2020.7.30
    2020.7.29
    2020.7.28
    2020.7.27
    2020.7.26 + 周报(3)
    2020.7.25
  • 原文地址:https://www.cnblogs.com/tenlee/p/4658306.html
Copyright © 2020-2023  润新知