用 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP