单词替换

GitHub跳转原题关系图返回列表

按单词切分句子,逐词比较并替换,再以空格重新连接。

OJ: noi_openjudge

题目 ID: ch0107-21

难度:入门

标签:字符串模拟python

日期: 2026-07-30 23:01

题意

将句子中所有与指定单词完全相同的单词替换为新单词。

思路

按空格切分为单词,生成新单词序列后用空格连接。只对完整单词做相等比较,不会误替换单词内部的子串。

代码

Python代码

python
sentence = input()
old_word = input().strip()
new_word = input().strip()

words = sentence.split(" ")
print(" ".join(new_word if word == old_word else word for word in words))

C++代码

cpp
#include <cstdio>
#include <cstring>


char str[1000][100];
int main(){
    int i = 0;
    while(1){
        int ret = scanf("%s",str[++i]);
        if ( ret == EOF)
            break;
    }
    i--;
    char *s1 = str[i-1];
    char *s2 = str[i];
    int j;
    for(j=1;j<=i-2;j++){
        if( strcmp(str[j],str[i-1]) == 0){
            printf("%s ",s2);
        }
        else
            printf("%s ",str[j]);
    }
    return 0;
}

复杂度

设句子长度为 nn,时间和输出空间复杂度均为 O(n)O(n)

总结

按单词替换应先切词,再比较完整词。