用C++統計句子中迴文單詞的個數
給定一個包含英文句子的字串,目標是找到字串中迴文單詞的數量。迴文詞是指從開頭或結尾讀都具有相同字母順序的單詞。如果句子是“Madam speaks good Malayalam”,那麼迴文單詞的數量是2。(Madam 和 Malayalam)
注意 − 單詞可以包含大寫和小寫字母。
讓我們透過例子來理解。
輸入 − str = "My Mom and Anna left at Noon";
輸出 − 句子中迴文單詞的數量為 − 3
解釋 − 上述句子中的迴文單詞為 − Mom、Anna 和 Noon。(字母的大小寫無關緊要)
輸入 − str= “I am at level 121 in Racecar game”
輸出 − 句子中迴文單詞的數量為 − 4
解釋 − 上述句子中的迴文單詞為 − I、level、121、Racecar。(字母的大小寫無關緊要)
下面程式中使用的方法如下
我們將在句子中以空格“ ”為分隔符獲取每個單詞,並將其傳遞給一個函式。該函式將單詞的字元轉換為小寫。現在從單詞的第一個字元開始遍歷,並將word[0]與word[length-1]、word[1]與word[length-2]等進行比較。如果出現任何不匹配,則中斷迴圈,否則返回true。
使用包含句子的字串陣列 str[]。
函式 check(string extra) 獲取一個字串,如果字串是迴文則返回 true,否則返回 false。
計算字串 extra 的長度為 len=extra.length()。
使用 (extra.begin(), extra.end(), extra.begin(), ::tolower); 將整個字串轉換為小寫。
使用 for 迴圈從單詞的索引 0 開始遍歷到索引 < len。
比較 extra[i] == extra[len-1]。如果出現不匹配,則返回 false。否則返回 true。
函式 palindrome(string str, int length) 獲取一個句子及其長度,並返回其中迴文單詞的數量。
將初始計數設定為 0。
使用臨時字串 extra="" 來選擇和儲存單個單詞。
使用 for 迴圈從索引 0 開始遍歷句子到 i < length。
獲取臨時字元 temp=str[i]。
如果 temp 不是空格,則將其新增到 extra 以構成一個單詞。
如果 temp 不是空格,則如果 (check(extra)) 返回 true,則計數加 1。
再次將 extra 設定為 ""。
最後的計數將包含迴文單詞的總數。
返回計數作為結果。
示例
#include <bits/stdc++.h>
using namespace std;
bool check(string extra){
int len = extra.length();
transform(extra.begin(), extra.end(), extra.begin(), ::tolower);
for (int i = 0; i < len; i++,len--){
if (extra.at(i) != extra.at(len - 1)){
return false;
}
}
return true;
}
int palindrome(string str, int length){
int count = 0;
string extra = "";
for (int i = 0; i < length; i++){
char temp = str.at(i);
if (temp != ' '){
extra = extra + temp;
}
else{
if (check(extra))
{ count++; }
extra = "";
}
}
return count;
}
int main(){
string str = "nitin wants nitin for his company named nitin after nitin";
str = str + " ";
int length = str.length();
cout<<"Count of palindrome words in a sentence are: "<<palindrome(str, length)<<endl;
return 0;
}輸出
如果我們執行上述程式碼,它將生成以下輸出:
Count of palindrome words in a sentence are: 4
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP