ที่นี่เราจะเห็นโปรแกรมหนึ่งที่สามารถบอกได้ว่าสองสตริงเป็นการหมุนของกันและกันหรือไม่ การหมุนของสตริงเป็นเหมือน −
สมมติว่าสองสตริงคือ S1 ='HELLO' และ S2 ='LOHEL' ดังนั้นจึงเป็นการหมุนเวียนกัน โดยการหมุน HELLO ไปทางซ้าย 3 ตำแหน่งจะเป็น LOHEL
เพื่อแก้ปัญหานี้ เราจะเชื่อมสตริงแรกกับตัวเอง จากนั้นตรวจสอบว่ามีสตริงที่สองอยู่ในสตริงที่ต่อกันหรือไม่ ดังนั้นสำหรับ HELLO จะเป็น HELLOHEL โล จากนั้นสตริงที่ต่อกันนี้จะมี LOHEL [สวัสดี].
อัลกอริทึม
isRotation(str1, str2)
begin if lengths of str1, and str2 are not same then return false; temp := concatenate str1 with str1 itself if temp contains str2, then return true otherwise return false end
ตัวอย่าง
#include<iostream>
using namespace std;
bool isRotation(string str1, string str2){
if(str1.length() != str2.length())
return false;
string con_str = str1 + str1;
if(con_str.find(str2) != string::npos){
return true;
} else {
return false;
}
}
main() {
string str1, str2;
cout << "Enter two strings: ";
cin >> str1 >> str2;
if(isRotation(str1, str2)){
cout << "Two strings are rotation of each other";
} else {
cout << "Two strings are not rotation of each other";
}
} ผลลัพธ์
Enter two strings: STACK CKSTA Two strings are rotation of each other