Follow up: group isomorphic strings together


  • 0
    S

    Follow up question:
    Given an array with strings, group the isomorphic strings into groups.
    For example:
    Given ['aba', 'zzz','dccb', 'ded', 'ccc', 'aaa', 'cbba']
    Return [ [ 'zzz', 'ccc', 'aaa' ], [ 'aba', 'ded' ], [ 'dccb', 'cbba' ] ]

    My Javascript solution:
    Build a hash function to record the occurrence of each character for every string,
    and build up a map according to the hash value.
    Loop through the map again and save group results into the result.

    Please let me know if you have any better ideas!

    // Given a string array, group the isomorphic strings into groups.
    function isomorphicGroup(arr) {
      if (arr === null || arr.length === 0) return [];
      let result = [];
    
      // Use a helper method to build unique hash for different patterns
      function encoding(str) {
        let i = 0;
        let hash = "";
        let map = {};
        for(let c of str) {
          if (map[c] === undefined) {
            map[c] = i++;
            hash += map[c];
          }
        }
        return hash;
      }
      let isoMap = {};
      for (let str of arr) {
        // Unique pattern
        let hashStr = encoding(str);
        // Group the same pattern strings into same array.
        if (isoMap[hashStr] === undefined) {
          isoMap[hashStr] = [str];
        } else {
          isoMap[hashStr].push(str);
        }
      }
      for (let key in isoMap) {
        result.push(isoMap[key]);
      }
      return result;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.