|
| 1 | +/* |
| 2 | +
|
| 3 | +
|
| 4 | + -* Valid Anagram *- |
| 5 | +
|
| 6 | +Given two strings s and t, return true if t is an anagram of s, and false otherwise. |
| 7 | +
|
| 8 | +An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. |
| 9 | +
|
| 10 | +
|
| 11 | +
|
| 12 | +Example 1: |
| 13 | +
|
| 14 | +Input: s = "anagram", t = "nagaram" |
| 15 | +Output: true |
| 16 | +Example 2: |
| 17 | +
|
| 18 | +Input: s = "rat", t = "car" |
| 19 | +Output: false |
| 20 | +
|
| 21 | +
|
| 22 | +Constraints: |
| 23 | +
|
| 24 | +1 <= s.length, t.length <= 5 * 104 |
| 25 | +s and t consist of lowercase English letters. |
| 26 | +
|
| 27 | +
|
| 28 | +Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case? |
| 29 | +
|
| 30 | +*/ |
| 31 | + |
| 32 | +class A { |
| 33 | + bool isAnagram(String s, String t) { |
| 34 | + if (s.length != t.length) return false; |
| 35 | + final List<String> listOne = s.split('')..sort(); |
| 36 | + final List<String> listTwo = t.split('')..sort(); |
| 37 | + |
| 38 | + return listOne.join() == listTwo.join(); |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +class B { |
| 43 | + bool isAnagram(String s, String t) { |
| 44 | + if (s.length != t.length) return false; |
| 45 | + final List<String> listOne = s.split(''); |
| 46 | + final List<String> listTwo = t.split(''); |
| 47 | + for (int i = 0; i < listOne.length; i++) { |
| 48 | + int index = listTwo.indexWhere((element) => element == listOne[i]); |
| 49 | + if (index >= 0) { |
| 50 | + listTwo.removeAt(index); |
| 51 | + } else { |
| 52 | + return false; |
| 53 | + } |
| 54 | + } |
| 55 | + return true; |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +class C { |
| 60 | + bool isAnagram(String s, String t) { |
| 61 | + if (s.length != t.length) return false; |
| 62 | + final Map<String, int> mapOne = {}; |
| 63 | + final Map<String, int> mapTwo = {}; |
| 64 | + |
| 65 | + for (int i = 0; i < s.length; i++) { |
| 66 | + mapOne[s[i]] = (mapOne[s[i]] ?? 0) + 1; |
| 67 | + mapTwo[t[i]] = (mapTwo[t[i]] ?? 0) + 1; |
| 68 | + } |
| 69 | + final mapOneKeys = mapOne.keys.toList(); |
| 70 | + final mapOneValues = mapOne.values.toList(); |
| 71 | + |
| 72 | + for (int i = 0; i < mapOne.length; i++) { |
| 73 | + final key = mapOneKeys[i]; |
| 74 | + final value = mapOneValues[i]; |
| 75 | + |
| 76 | + if (mapTwo[key] != value) return false; |
| 77 | + } |
| 78 | + return true; |
| 79 | + } |
| 80 | +} |
0 commit comments