題目詳情:
給你一個字(zi)符串數組(zu) words ,請你找出所有在 words 的(de)(de)每個字(zi)符串中都出現的(de)(de)共用(yong)字(zi)符( 包括重復字(zi)符),并(bing)以數組(zu)形(xing)式返回。你可以按 任(ren)意順序(xu) 返回答案。
示例:
輸入:words = ["bella","label","roller"]
輸出:["e","l","l"]
解題思路:
首先取數組中的第一個字符串 firstWord,然后遍歷它(ta)的每(mei)個字符。
對于每個字符,我們使用一個布爾變量 isCommon 來表示該字符是否在所有字符串中都出現。初始時,將 isCommon 設置為 true。
然后,我們遍歷除了第一個字符串之外的其他字符串。對于每個字符串,我們判斷它是否包含當前字符。如果不包含,則說明該字符不是共用字符,將 isCommon 設置為 false,并(bing)跳出(chu)循環。否則,我們從字(zi)符(fu)串中(zhong)刪除該字(zi)符(fu),以避(bi)免重復(fu)計數。
最后,如果 isCommon 為 true,則(ze)表示當前字符(fu)是共用字符(fu),將其添加到(dao)結果數組中。
重復上述步驟,直到遍歷完 firstWord 的所有字符。
最后,返回結果數組 result。
代碼實現:
function commonChars(words) {
  const result = [];
  
  const firstWord = words[0];
  for (const char of firstWord) {
    let isCommon = true;
    
    for (let i = 1; i < words.length; i++) {
      if (!words[i].includes(char)) {
        isCommon = false;
        break;
      } else {
        words[i] = words[i].replace(char, '');
      }
    }
    
    if (isCommon) {
      result.push(char);
    }
  }
  
  return result;
}
// 示例輸入
const words = ["bella", "label", "roller"];
// 調用函數并輸出結果
console.log(commonChars(words));