首页 > 解决方案 > 如果字符串中的字母不在字符数组中,则用“#”切换它们

问题描述

void funOne(char a[], string b, int aL, int bL) {
    int cnt[aL]={0};
    for(int i=0; i<bL; i++) {
        for(int j=0; j<aL; j++) {
            if((char)b[i]==a[j]; {
                cnt[j]++;
                break;
            }
        }
    }
    for(int i=0; i<bL; i++) {
        for(int j=0; j<aL; j++) {
            if((char)b[i]==a[j]&&cnt=0) {
                b[i]='#';
                break;
            }
        }
    }

有一个字符arr[]={'H', 't', 'h', 's', 'e', 'i'};和一个字符串"Sherlock Holmes is a fiction private detective"。不在数组中的每个字符都应替换"#"为字符串中的字符。

输出应该是

"She##### H###es is # #i#ti#n ##i##te #ete#ti#e"

我的代码有问题,但我不知道是什么。

标签: c++arraysfunctionchar

解决方案


如果您正在寻找解决此问题的最佳解决方案,请查看此内容!:) 这个想法是散列数组中的所有字符,然后每次遍历输入字符串时检查它们的成员资格( Checking - O(1) )。

arr = set(['H', 't', 'h', 's', 'e', 'i'])
arr.add(' ') #so that whitespaces don't get replaced
input = 'Sherlock Holmes'
output = str()
for char in input:
    if char not in arr:
        output += '#'
    else:
        output += char

print output

此代码在 O(n) 时间内运行,但空间为 O(n)。


推荐阅读