在C ++中以字符串形式显示所有有趣的单词

在这个问题上,我们有一个句子。我们的任务是从句子中打印出所有有趣的单词。

有趣的单词是符合以下条件的单词-字符串的相邻字符与其反向字符串之间的绝对差相等。

|string[0] - string[1]| = |revstring[0]-revstring[1]|

让我们以一个例子来了解问题-

Input: string = ‘ABRS’
Output: Yes
Explanation:
Reverse string = SRBA
|A-B| = 1 = |S-R|
|B-R| = 16 = |R-B|
|B-A| = 1 = |R-S|

为了解决这个问题,我们必须从给定的句子中提取每个字符串。如果字符串是一个有趣的字符串,请打印。

检查有趣的字符串-为此,我们将从两端(即从头到尾)遍历字符串。并比较字符串的相邻字符之间的绝对差异,如果差异不相同,则返回false。

以下代码将实现我们的逻辑-

示例

#include <iostream>
#include<string.h>
using namespace std;
bool isFunny(string word){
   int i = 1;
   int j = word.length() - 2;
   for (int i = 0; i < word.length(); i++)
      word[i] = tolower(word[i]);
   while (i <= j){
      if (abs(word[i] -
         word[i - 1]) != abs(word[j] -
      word[j + 1]))
      return false;
      i++;
      j--;
   }
   return true;
}
void printFunnyWords(string str){
   str +=" ";
   string word = "";
   for (int i = 0; i < str.length(); i++){
      char ch = str[i];
      if (ch!=' ')
         word += ch;
      else{
         if (isFunny(word))
            cout<<word<<"\t";
         word = "";
      }
   }
}
int main(){
   string sentence = "hello, i love malayalam langauge";
   cout<<"All funny words of the string '"<<sentence<<"' are :\n";
   printFunnyWords(sentence);
   return 0;
}

输出结果

All funny words of the string 'hello, i love malayalam langauge' are :
i malayalam