在 C++ 中計算單詞數量,其中第 i 個字母是給定單詞的第 (i-1) 個、第 i 個或第 (i+1) 個字母
給定一個字串 str[] 作為輸入。目標是從 str[] 中計算出與 str[] 長度相同的單詞,並且字母位置滿足以下條件:第 i 個字母被替換為第 (i-1) 個、第 i 個或第 (i+1) 個字母。
對於第一個字母,替換將來自第 i 個或第 i+1 個位置。
對於最後一個字母,替換將來自第 i-1 個或第 i 個位置。
讓我們透過示例來理解。
輸入 − str[] = “TPP”
輸出 − 第 i 個字母是給定單詞的第 (i-1) 個、第 i 個或第 (i+1) 個字母的單詞數量為 - 4
解釋
Replacing T by T (i)th or 1st P (i+1)th = TPP, PPP Replacing 1st P by T (i-1)th, P (i)th, or P(i+1)th = TTP, TPP, TPP Replacing 2nd P by P(i-1)th or P(i)th = TPP, TPP Unique combination of replacements: TPP, PPP, TTP, PTP
輸入 − str = “aaa”
輸出 − 第 i 個字母是給定單詞的第 (i-1) 個、第 i 個或第 (i+1) 個字母的單詞數量為:1
解釋
Replacing a by a (i)th or 2nd a (i+1)th = aaa, aaa Replacing 2nd a by a (i-1)th, a (i)th, or a(i+1)th = aaa, aaa, aaa Replacing 3rd a by a(i-1)th or a(i)th = aaa, aaa Unique combination of replacements: aaa
下面程式中使用的方法如下
我們知道,對於每個字母,我們有三種可能性。如果對於當前字母 i,所有 (i-1)th、ith、(i+1)th 都是不同的,那麼我們有 3 個選項。如果兩個相同,我們有 2 個選項,如果全部相同,則只有一個選項。
因此,我們將遍歷字串並檢查唯一性,並根據字母乘以 3、2 或 1。對於第一個和最後一個字母,我們將檢查唯一性並以類似的方式乘以 2 或 1。
將字串 str[] 作為字元陣列。
函式 total(char str[], int length) 獲取字串並返回 str[] 中第 i 個字母是給定單詞的第 (i-1) 個、第 i 個或第 (i+1) 個字母的單詞數量。
將初始計數設定為 1。str[] 中的單詞本身。
如果只有一個字母,長度將為 1,返回 1。
檢查索引 0 處的第一個字母。如果它與第二個相同,則 str[0]==str[1],則將計數乘以 1
如果它們不同,則將計數乘以 2。
現在使用 for 迴圈從索引 i=1 到 i<length-1 遍歷從第二個字母到倒數第二個字元。
對於索引 i 處的每個字母。檢查 str[i] 是否與 str[i-1] 或 str[i+1] 相同。如果是,則將計數乘以 1。
如果任意兩個相同,則將計數乘以 2。
否則將計數乘以 3。
對於最後一個字元,檢查 str[i-1]==str[i]。如果為真,則將計數乘以 1。否則乘以 2
最後,我們將獲得這些不同單詞的計數。
返回計數作為結果。
示例
#include<bits/stdc++.h>
using namespace std;
int total(char str[], int length){
int count = 1;
if (length == 1){
return count;
}
if (str[0] == str[1]){
count = count * 1;
}
else{
count = count * 2;
}
for (int j=1; j<length-1; j++){
if (str[j] == str[j-1] && str[j] == str[j+1]){
count = count * 1;
}
else if (str[j] == str[j-1]){
count = count * 2;
}
else if(str[j] == str[j+1]){
count = count * 2;
}
else if(str[j-1] == str[j+1]){
count = count * 2;
}
else{
count = count * 3;
}
}
if (str[length - 1] == str[length - 2]){
count = count * 1;
}
else{
count = count * 2;
}
return count;
}
int main(){
char str[] = "TPP";
int length = strlen(str);
cout<<"Count of words whose i-th letter is either (i-1)-th, i-th, or (i+1)-th letter of given word
are: "<<total(str, length) << endl;
return 0;
}輸出
如果我們執行以上程式碼,它將生成以下輸出 -
Count of words whose i-th letter is either (i-1)-th, i-th, or (i+1)-th letter of given word are: 4
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP