String Permutations

Given a string, generate a list of all possible permutations of the string.

func permutations(string: String) -> [String] {
  if string.count == 0 {
    return [""]
  }
  
  var string = string
  let char = string.removeFirst()

  let strings = permutations(string: string)

  var newStrings = [String]()
  
  for str in strings {
    for i in 0 ... str.count {
      var newString = str
      
      if i < str.count {
        let index = str.index(str.startIndex, offsetBy:i)
        newString.insert(char, at: index)
      }
      else {
        newString += String(char)
      }
      
      newStrings.append(newString)
    }
  }
  
  return newStrings
}

let p = permutations(string:"abc")
print("p \(p)")
Scroll to top