Generating all permutations of a given string

前端 未结 30 2096
我寻月下人不归
我寻月下人不归 2020-11-21 06:35

What is an elegant way to find all the permutations of a string. E.g. permutation for ba, would be ba and ab, but what about longer st

30条回答
  •  被撕碎了的回忆
    2020-11-21 06:53

    String permutaions using Es6

    Using reduce() method

    const permutations = str => {
      if (str.length <= 2) 
      return str.length === 2 ? [str, str[1] + str[0]] : [str];
      
      return str
        .split('')
        .reduce(
          (acc, letter, index) =>
            acc.concat(permutations(str.slice(0, index) + str.slice(index + 1)).map(val => letter + val)),
          [] 
        );
    };
    
    console.log(permutations('STR'));

提交回复
热议问题