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

สตริงหนึ่งซ้ำได้อีกสตริงหนึ่งหรือไม่ใน JavaScript


ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงสองตัว str1 และ str2 เป็นอาร์กิวเมนต์แรกและสอง

ฟังก์ชันควรคืนจำนวนครั้งน้อยที่สุดที่ควรซ้ำ str1 ทำให้ str2 เป็น substring ของมัน หากเป็นไปไม่ได้ ให้คืน -1

ตัวอย่างเช่น หากอินพุตคือ

Input

const str1 = 'wxyz'; 
const str2 = 'yzwxyzwx';

Output

const output = 3;

คำอธิบายผลลัพธ์

เราคืน 3 เพราะการซ้ำ str1 สามครั้ง "wxyzwxyzwxyz" จะทำให้ str2 เป็น substring

ตัวอย่าง

โค้ดด้านล่างนี้

const str1 = 'wxyz'; 
const str2 = 'yzwxyzwx'; 
const countRepeat = (str1 = '', str2) => {
  let i = 1;
  let current = str1;
  while (true) {
    if (current.indexOf(str2) >= 0) {
      return i;
    }
    if ((current.length > str2.length * 2) && i > 2) {
      return -1;
    }
    current += str1;
    i += 1;
  }
};
console.log(countRepeat(str1, str2));

ผลลัพธ์

3