สมมติว่าเรามีสตริงสองตัวคือ s และ t เราต้องการตรวจสอบว่า s เป็นการหมุน (rotation) ของ t หรือไม่ กล่าวคือ สามารถได้ t จากการหมุน s ได้หรือไม่
ตัวอย่างเช่น หาก input เป็น s = "helloworld" และ t = "worldhello" ผลลัพธ์จะเป็น true
วิธีแก้ปัญหา
- ถ้าความยาวของ
sและtไม่เท่ากัน ให้คืนค่าfalseทันที - นำ
sมาต่อกับตัวเองอีกครั้ง (s + s) - ตรวจสอบว่า
tเป็น substring ของสตริงที่ต่อกันนี้หรือไม่ ถ้าใช่ให้คืนtrueไม่ใช่ให้คืนfalse
ตัวอย่างโค้ด C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool solve(string s0, string s1) {
if(s0.size() != s1.size())
return false;
string s = s0 + s0;
return s.find(s1) != string::npos;
}
};
int main() {
Solution ob;
cout << (ob.solve("helloworld", "worldhello"));
}
Input
"helloworld", "worldhello"
Output
1