Similar String Group

相似字符串分组问题

Similar-String-Group.js

const arrs = ["tars","rats","arts","star"];
//比较两个字符串是否相似
const isSimilar = (str1, str2)=>{
  const obj = {};
  let counter = 0;
  for (let i = 0 ; i < str1.length ; i++) {
    if (str1[i] !== str2[i]) {
      counter++;
      obj[str1[i]] = str2[i];
    }
  }
  return (counter === 2 && oppositeObj(obj))? true : false
}

const oppositeObj = (obj)=>{
  const keys = Object.keys(obj);
  const length = keys.length;
  if (length!=2){
    return false;
  }
  if (obj[keys[0]] !== keys[1]) {
    return false;
  }
  return true;
}

const similarStringGroup = (arr = [])=>{
  const group = [[arr[0]]];
  for (let i = 1 ; i< arr.length; i++) {
    let match = false;
    for (let j = 0 ; j < group.length; j++) {
      for (let k = 0 ; k< group[j].length ; k++) {
        const booleanMatch =  isSimilar(group[j][k],arr[i]);
        if (booleanMatch) {
          group[j].push(arr[i]);
          match = true;
          break;
        }
      }
      if (match===true) {
        break;
      }
    }
    if(match === false){ 
      group.push([arr[i]])
    }
  }
  return group.length
}
console.log(similarStringGroup(arrs));

版权声明:著作权归作者所有。

thumb_up 0 | star_outline 0 | textsms 0