给我们一个字符串str []作为输入。目的是对来自str []的单词进行计数,这些单词的长度与str []相同,并且具有字母位置,以使第i个字母在位置(i1)或(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)个字母的单词计数:
说明
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),第ith,(i + 1)个不同,则我们有3个选项。如果两个相同,我们有2个选项,如果全部相同,则只有一个选项。
因此,我们将遍历字符串并检查唯一性,然后根据字母乘以3、2或1。对于第一个和最后一个字母,我们将检查唯一性并以类似方式乘以2或1。
将字符串str []作为字符数组。
函数total(char str [],int length)接收字符串并返回第i个字母为给定第(i-1)个,第i个或第(i + 1)个字母的单词计数str []中的单词。
将初始计数设为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]。如果为true,则将count乘以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