ในปัญหานี้ เราจะได้รับประโยค งานของเราคือพิมพ์สตริงทั้งหมดจากประโยคที่เป็น คำตลก
คำตลก เป็นคำที่เป็นไปตามเงื่อนไข - ความแตกต่างที่แน่นอนระหว่างอักขระที่อยู่ติดกันของสตริงและสตริงย้อนกลับจะเท่ากัน
|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|
เพื่อแก้ปัญหานี้ เราต้องแยกแต่ละสตริงออกจากประโยคที่กำหนด และพิมพ์ว่าสตริงนั้นเป็นสตริงที่ตลกหรือไม่
ตรวจสอบสตริงที่ตลก − สำหรับสิ่งนี้ เราจะสำรวจสตริงจากปลายทั้งสอง นั่นคือ จากจุดเริ่มต้นและจากจุดสิ้นสุด และเปรียบเทียบผลต่างสัมบูรณ์ระหว่างอักขระที่อยู่ติดกันของสตริงและคืนค่าเท็จหากความแตกต่างไม่เหมือนกัน
โค้ดด้านล่างจะใช้ตรรกะของเรา -
ตัวอย่าง
#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