单词相同字符数

Python挑战练习-进阶练习41

编写一个程序来计算两个给定单词之间相同字符的数量。

需要考虑字符是区分大小写的(即aA是不同的字符)。

例如,单词cookiecool有两个字符相同:co。因此,输出应该是2

另一方面,单词Blowbeer没有相同的字符,因为Bb视为不同的字符。

  • 定义函数shared_chars_count(),有两个参数:word1word2

  • 该函数应返回两个单词中相同字母的数量。

分析:

  • 考虑字符区分大小写

  • 一个相同字符计数一次

相同字符计数一次,针对这一点,可以先把 word1和word2转成集合,这样word1和word2就都不含有重复出现的字母,然后再比较即可。这个“比较”可以利用集合之间的交集运算,再获取交集中元素个数,就能知道两个给定单词之间相同字符的数量。

def shared_chars_count(word1, word2):
    set_word1 = set(word1)
    set_word2 = set(word2)
    common_set = set_word1.intersection(set_word2)
    return len(common_set)
# 获取输入
word1 = input()
word2 = input()

# 调用函数
print(shared_chars_count(word1, word2))

 

以下是几种使用C++统计字符串中单词数的方法: ### 方法一:通过统计空格数量 此方法基于单词数比空格数多1的原理,通过统计输入字符串中的空格数量计算单词数。 ```cpp #include <string> #include <iostream> using namespace std; int main(){ string s; cout << "请输入一句话(以空格分割单词):"; getline(cin, s); int count = 0; for(int i = 0; i <= s.size(); i++){ if(s[i] == ' '){ count += 1; } } cout << "这句话有" << count+1 << "个单词"; // 单词数比空格多1 return 0; } ``` 这种方法简单直接,但要求输入的字符串中单词之间只能有一个空格分隔。[^1] ### 方法二:利用`while`循环统计空格 同样是统计空格数量,只是使用`while`循环来遍历字符串。 ```cpp #include<iostream> #include<string> using namespace std; int main() { string str; cout << "请输入一串字符(以一个空格为分隔不同单词)" << endl; getline(cin, str); int i = 0, count = 0; while (i<=str.length()){ if (str[i] == ' ') count++; i++; } count++; cout << "本字符串共有" << count << "个单词" << endl; system("pause"); return 0; } ``` 该方法与方法一类似,对输入字符串格式有相同要求。[^2] ### 方法三:处理连续空格的情况 此方法考虑了连续空格的情况,通过一个标志位`flag`来判断是否遇到新的单词。 ```cpp class Solution { public: int countSegments(string s) { int res = 0; bool flag = true; for (int i = 0; i < s.size(); ++ i) { if (s[i] != ' ' && flag) { res ++; flag = false; } else { if (s[i] == ' ' && i < s.size() - 1 && s[i + 1] == ' ') flag = false; else if (s[i] == ' ' && flag == false) flag = true; } } return res; } }; ``` 在使用时,可以这样调用: ```cpp #include <iostream> #include <string> int main() { Solution sol; string input = "Hello, my name is John"; int wordCount = sol.countSegments(input); std::cout << "单词数: " << wordCount << std::endl; return 0; } ``` 这种方法能够处理连续空格的情况,更具通用性。[^3] ### 方法四:另一种处理连续空格的方式 通过判断当前字符和下一个字符的情况来统计单词数。 ```cpp class Solution { public: int countSegments(string s) { int count = 0 ; for(int i = 0; i < s.length();i++) { if (i == 0 && s[i] != ' ') { count++; } if(s[i]==' '&&i+1<s.length()&&s[i+1]!=' ') count++; } return count; } }; ``` 使用示例: ```cpp #include <iostream> #include <string> int main() { Solution sol; string input = "Hello, my name is John"; int wordCount = sol.countSegments(input); std::cout << "单词数: " << wordCount << std::endl; return 0; } ``` 该方法也能处理连续空格的情况。[^4]
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值