stringPermutations function

List<String> stringPermutations(
  1. String s
)

Generate All Permutations of a String: Returns a list of all unique permutations.

Implementation

List<String> stringPermutations(String s) {
  final result = <String>[];
  void permute(List<String> chars, int l) {
    if (l == chars.length - 1) {
      result.add(chars.join());
      return;
    }
    final seen = <String>{};
    for (int i = l; i < chars.length; i++) {
      if (seen.add(chars[i])) {
        chars.swap(l, i);
        permute(chars, l + 1);
        chars.swap(l, i);
      }
    }
  }

  permute(s.split(''), 0);
  return result;
}