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

ผลรวม ASCII น้อยที่สุดของตัวอักษรที่ลบเพื่อทำให้สตริงเท่ากันใน JavaScript


ปัญหา

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

ฟังก์ชันควรหาและคืนผลรวม ASCII น้อยที่สุดของตัวอักษรที่ลบ เพื่อทำให้สตริงทั้งสองเท่ากัน

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

Input

const str1 = 'sea'; 
const str2 = 'eat';

Output

const output = 231;

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

การลบ "s" จาก "sea" เพิ่มค่า ASCII ของ "s" (115) เข้าไปในผลรวม

การลบ "t" จาก "eat" เพิ่ม 116

ท้ายที่สุดทั้งสองสตริงเท่ากัน และ 115 + 116 = 231 เป็นผลรวมต่ำสุด

ตัวอย่าง

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

const str1 = 'sea'; 
const str2 = 'eat'; 
const minimumSum = (str1 = '', str2 = '') => {
  const chartCode = (s = '') => {
    let code = 0;
    for (const c of s) {
      code += c.charCodeAt(0);
    }
    return code;
  };
  let prev = new Array(str2.length + 1).fill(0);
  for (let ind1 = str1.length; ind1 >= 0; ind1--) {
    const current = new Array(str2.length + 1).fill(0);
    for (let ind2 = str2.length; ind2 >= 0; ind2--) {
      if (ind1 === str1.length) {
        current[ind2] = chartCode(str2.slice(ind2));
      } else if (ind2 === str2.length) {
        current[ind2] = chartCode(str1.slice(ind1));
      } else if (str1[ind1] === str2[ind2]) {
        current[ind2] = prev[ind2 + 1];
      } else {
        current[ind2] = Math.min(
          prev[ind2] + (str1[ind1]).charCodeAt(0),
          current[ind2 + 1] + (str2[ind2]).charCodeAt(0),
        );
      }
    }
    prev = current;
  }
  return prev[0];
};
console.log(minimumSum(str1, str2));

ผลลัพธ์

231