Accepted SWIFT 1 Liner solution and HashTable solution in O(n)


  • 0
    I

    The easiest solution O(nlogn) at a performance hit is just to compare the 2 strings sorted.

    class Solution {
        func isAnagram(_ s: String, _ t: String) -> Bool {
            return s.characters.sorted() == t.characters.sorted()
        }
    }
    

    Second solution O(n) is to have a dictionary to keep track of number of appearances of each char in s then deduct 1 as the same char is in t. If no char in t found in s or the dict is not empty at the end of the loop return false.

    class Solution {
        func isAnagram(_ s: String, _ t: String) -> Bool {
            var dict = [Character: Int]()
            for c in s.characters {
                dict[c] = (dict[c] ?? 0) + 1
            }
            
            for c in t.characters {
                if let val = dict[c] {
                    if val-1 == 0 {
                        dict.removeValue(forKey: c)
                    } else {
                        dict[c] = val-1
                    }
                } else {
                    return false
                }
            }
            
            return dict.isEmpty ? true : false
        }
    }

Log in to reply
 

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