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

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

题目大意:

看中文

样例解释:

解题思路:

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

错误的代码

int k = 0, i;
    for(i = 0; str[i+1]; i++)
    {
        printf("%d %c\n", 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\n", 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",其实是”vv\0awyh", 故 在代码的第7行,又一次加了1,会跳过 '\0',从而导致继续向后读,所以就输出了 "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\n", 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\n", 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\n");
        else
            printf("No\n");
    }
    return 0;
}

  

转载于:https://www.cnblogs.com/tenlee/p/4658306.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值