이 문제에서는 문장이 주어집니다. 우리의 임무는 재미있는 단어인 문장의 모든 문자열을 출력하는 것입니다.
재미있는 단어 조건 뒤에 오는 단어 - 문자열의 인접 문자와 역 문자열 간의 절대 차이가 동일합니다.
|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