c++ - 如果字符串中的字母不在字符数组中,则用“#”切换它们
问题描述
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"
我的代码有问题,但我不知道是什么。
解决方案
如果您正在寻找解决此问题的最佳解决方案,请查看此内容!:) 这个想法是散列数组中的所有字符,然后每次遍历输入字符串时检查它们的成员资格( 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)。
推荐阅读
- c# - 从另一个文件/类调用非静态方法
- python - 我怎么能用记事本写的东西做一个if语句
- python - 在 Python 中为字段名称添加前缀
- python - Keras CNN:验证数据集不包括所有类时的语法
- android - 为什么openCV4Android的bitmapToMat只支持RGBA_8888和RGB_565?
- r - 如何使用预测功能获取新列
- javascript - 如何使一个按钮在单击另一个按钮时消失?
- java - 如何从以 DocumentReference 作为参数的方法中获得双重返回?
- c# - Windows 服务在 1 天后停止工作
- php - Phalcon项目索引找不到控制器,服务器错误为404 not found