用 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