Checking if two strings are permutations of each other

前端 未结 30 1073
感情败类
感情败类 2020-12-05 08:19

How to determine if two strings are permutations of each other

30条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 09:09

    • Sort the two strings's characters.
    • Compare the results to see if they're identical.

    Edit:

    The above method is reasonably efficient - O(n*log(n)) and, as others have shown, very easy to implement using the standard Java API. Even more efficient (but also more work) would be counting and comparing the occurrence of each character, using the char value as index into an array of counts.

    I do not thing there is an efficient way to do it recursively. An inefficient way (O(n^2), worse if implemented straightforwardly) is this:

    • If both strings consist of one identical character, return true
    • Otherwise:
      • remove one character from the first string
      • Look through second string for occurrence of this character
      • If not present, return false
      • Otherwise, remove said character and apply algorithm recursively to the remainders of both strings.

提交回复
热议问题