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

Cha Cha Slide C++: ตรวจสอบว่า String เป็นการหมุนของอีก String หนึ่งหรือไม่

สมมติว่าเรามีสตริงสองตัวคือ s และ t เราต้องการตรวจสอบว่า s เป็นการหมุน (rotation) ของ t หรือไม่ กล่าวคือ สามารถได้ t จากการหมุน s ได้หรือไม่

ตัวอย่างเช่น หาก input เป็น s = "helloworld" และ t = "worldhello" ผลลัพธ์จะเป็น true

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

  1. ถ้าความยาวของ s และ t ไม่เท่ากัน ให้คืนค่า false ทันที
  2. นำ s มาต่อกับตัวเองอีกครั้ง (s + s)
  3. ตรวจสอบว่า 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