ภาพรวม
เราต้องเขียนฟังก์ชันที่รับสตริงสองสตริง str1 และ str2 กำหนดว่า str2 เป็นเวอร์ชันหมุน (rotated) ของ str1 หรือไม่
ตัวอย่าง
const str1 = 'abcde';
const str2 = 'cdeab';
ควรคืน true เพราะ str2 ทำได้จากการเลื่อน 'ab' ไปท้ายสตริงใน str1
ตัวอย่างโค้ด
const str1 = 'abcde';
const str2 = 'cdeab';
const isRotated = (str1, str2) => {
if(str1.length !== str2.length) {
return false;
}
if((str1.length || str2.length) === 0) {
return true;
}
for(let i = 0; i < str1.length; i++) {
const rotated = str1.slice(i).concat(str1.slice(0, i));
if(rotated === str2) {
return true;
}
}
return false;
};
console.log(isRotated(str1, str2));
ผลลัพธ์ในคอนโซล
true