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

หา Subsequence ที่ไม่ซ้ำกันและยาวที่สุดในอาร์เรย์สตริง (JavaScript)

Subsequence

ลำดับที่ได้จากการลบตัวอักษรบางส่วนโดยไม่เปลี่ยนลำดับ

ปัญหา

รับอาร์เรย์สตริง หาความยาวของ longest uncommon subsequence (subsequence ของสตริงหนึ่งที่ไม่ใช่ subsequence ของสตริงอื่นในอาร์เรย์) หากไม่มีคืน -1

ตัวอย่าง

const arr = ["aba", "cdc", "eae"];

ทั้งสามสตริงยาว 3 และไม่ซ้ำกัน → ผลลัพธ์ 3

โค้ดตัวอย่าง

const arr = ["aba", "cdc", "eae"]; 
const longestUncommon = (strs) => { 
  const map = {}; 
  const arr = []; 
  let max = -1, index = -1; 
  for(let i = 0; i < strs.length; i++){ 
    map[strs[i]] = (map[strs[i]] || 0) + 1; 
    if(map[strs[i]] > 1){ 
      if(max < strs[i].length){ max = strs[i].length; index = i; } 
    } 
  } 
  if(index === -1) { strs.forEach(el =>{ if(el.length > max) max = el.length; }); return max; } 
  for(let i = 0; i < strs.length; i++){ if(map[strs[i]] === 1) arr.push(strs[i]); } 
  max = -1; 
  for(let i = arr.length - 1; i >= 0; i--){ 
    let l = arr[i], d = 0; 
    for(let j = 0; j < strs[index].length; j++){ if(strs[index][j] === l[d]) d++; } 
    if(d === l.length){ let temp = arr[i]; arr[i] = arr[arr.length - 1]; arr[arr.length - 1] = temp; arr.pop(); } 
  } 
  arr.forEach(el =>{ if(el.length > max) max = el.length; }); 
  return max; 
}; 
console.log(longestUncommon(arr));

ผลลัพธ์

3