Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

พิมพ์ Funny Words ในประโยคใน C++

ภาพรวมปัญหา

ได้รับประโยค ต้องพิมพ์คำที่เป็น "Funny Words" ทั้งหมด

Funny Word คืออะไร?

คำที่ความต่างสัมบูรณ์ระหว่างตัวอักษรติดกันของคำเดิม และคำที่กลับหลัง (reverse) เท่ากันทุกคู่

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

ตัวอย่าง

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

วิธีแก้ปัญหา

  1. แยกคำจากประโยค
  2. ตรวจสอบแต่ละคำ: เปรียบเทียบความต่างสัมบูรณ์ของตัวอักษรติดกันจากหน้าและหลัง
  3. ถ้าทุกคู่เท่ากัน → เป็น Funny Word

ตัวอย่างโค้ด C++

#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;
}

ผลลัพธ์ (Output)

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