[Ybt advanced 2-1-3] word replacement

Word replacement

Topic link: ybt efficient advanced 2-1-3

Topic

Enter a string and end with a carriage return.

The string consists of several words separated by a space, and all words are case sensitive.

Now you need to replace one of the words with another word, and output the replaced string.

Ideas

The content of this question is actually very easy to implement. Every time a word is found, determine if it needs to be changed.
If so, output the changed, otherwise output the original.

But reading this question is very annoying and disgusting. (Anyway, I have been wrong for a long time)
Insert picture description here
(The first time, I used gets, and then the samples on Lunix will not be transferred, and the others are also RE)
(The second time, I changed to use getchar to come one One read in, and the result is all RE)
(The third time, the same reason, but after reading it for a long time, I found that the part dealing with the last word should have been output to n − 1 n-1n1 , I madennn , then RE)
(The fourth time, the problem found above was corrected, and TLE was found. It should be because there is no newline character in the last line, and the third while cannot read the newline character, so it can't exit, it's TLE )
(The fifth time, I used gets again, and then found that reading with gets will also read the newline characters)
(The sixth time, I asked GJY, tried getline, and found that the newline characters were still read. Then I thought A way: subtract one when calculating the length of the string, and then automatically ignore the final newline)

Code

#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>

using namespace std;

int sn, st, an, bn;
string s, a, b;
bool nc;

int main() {
    
    
	getline(cin, s);
	getline(cin, a);
	getline(cin, b);
	
	sn = s.size() - 1;//这样读入的时候会吧换行符读进去,所以算长度的时候要去掉换行符
	an = a.size() - 1;
	
	st = 0;
	nc = 1;
	for (int i = 0; i < sn; i++) {
    
    
		if (s[i] == ' ') {
    
    
			if (nc && (i - 1) - st + 1 == an) {
    
    
				cout << b;
				printf(" ");
			}
			else {
    
    
				for (int j = st; j <= i; j++)
					putchar(s[j]);
			}
			st = i + 1;
			nc = 1;
		}
		else {
    
    
			if (nc && (i - st + 1 > an || s[i] != a[i - st])) nc = 0;
		}
	}
	
	if (nc && (sn - 1) - st + 1 == an) {
    
    
		cout << b;
		printf(" ");
	}
	else {
    
    
		for (int j = st; j < sn; j++)
			putchar(s[j]);
	}
	
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43346722/article/details/112726363