กำหนดสตริงสองตัว a และ b ต้องการทราบว่า b สามารถได้มาจากการหมุน a ทิศทางเข็มนาฬิกาหรือทิศตรงข้ามเข็มนาฬิกา 2 ตำแหน่งหรือไม่
ตัวอย่าง Input-1
a = "google" b = "legoog"
Output
True
คำอธิบาย: "google" หมุนทิศตรงข้ามเข็มนาฬิกา 2 ตำแหน่ง → "legoog"
ตัวอย่าง Input-2
a = "tuorialst" b = "tutorials"
Output
False
แนวทางแก้ปัญหา
มี 2 กรณีต้องตรวจสอบ:
- Anticlockwise (ทิศตรงข้ามเข็มนาฬิกา): นำ 2 ตัวแรกไปต่อท้าย →
str.substring(2) + str.substring(0, 2) - Clockwise (ทิศตามเข็มนาฬิกา): นำ 2 ตัวท้ายไปต่อหน้า →
str.substring(len-2) + str.substring(0, len-2)
เงื่อนไขเบื้องต้น
- ถ้าความยาวไม่เท่ากัน → False
- ถ้าความยาว ≤ 2 → True (หมุน 2 ตำแหน่งจะกลับมาเดิม)
ตัวอย่างโค้ด (แก้ไขจากต้นฉบับที่มี bug)
public class Solution {
static boolean checkRotated(String str1, String str2) {
// ตรวจสอบความยาว
if (str1.length() != str2.length()) {
return false;
}
int len = str2.length();
if (len <= 2) {
return true; // หมุน 2 ตำแหน่งจะได้สตริงเดิม
}
// Anticlockwise: นำ 2 ตัวแรกไปท้าย
String anticlockwise = str2.substring(2) + str2.substring(0, 2);
// Clockwise: นำ 2 ตัวท้ายไปหน้า
String clockwise = str2.substring(len - 2) + str2.substring(0, len - 2);
return str1.equals(anticlockwise) || str1.equals(clockwise);
}
public static void main(String[] args) {
String s1 = "google";
String s2 = "legoog";
System.out.println(checkRotated(s1, s2) ? "True" : "False"); // True
// ทดสอบเพิ่มเติม
System.out.println(checkRotated("amazon", "onamaz") ? "True" : "False"); // True (clockwise)
System.out.println(checkRotated("hello", "llohe") ? "True" : "False"); // True (anticlockwise)
System.out.println(checkRotated("tuorialst", "tutorials") ? "True" : "False"); // False
}
}
ผลลัพธ์
True True True False
⚠️ หมายเหตุสำคัญ
โค้ดต้นฉบับมี bug ที่บรรทัด:
s2 = str2.substring(0,2) + str2.substring(0,2); // ผิด! ควรเป็น substring(len-2) + substring(0, len-2)
โค้ดด้านบนได้แก้ไขแล้ว
ความซับซ้อน
- Time Complexity: O(n) - substring และ equals ใช้เวลา O(n)
- Space Complexity: O(n) - สร้างสตริงใหม่ 2 ตัว