1
+ package practice
2
+
3
+ /* *
4
+ * @author EfeDaniel
5
+ * Link: https://leetcode.com/problems/valid-anagram/
6
+ * Progress: Done
7
+ */
8
+ object ValidAnagram {
9
+
10
+ /* *
11
+ * Main method Used mainly for testing purposes. Tests the input case:
12
+ * s = "anagram", t = "nagaram", output = true
13
+ * s= "a", t = "b", output = false
14
+ */
15
+ @JvmStatic
16
+ fun main (args : Array <String >) {
17
+ println (isAnagram(" anagram" , " nagaram" ))
18
+ println (isAnagram(" a" , " b" ))
19
+ }
20
+
21
+ /* *
22
+ * Solution Method. Sorts both strings and compares them with each other. If they are the same, they are anagrams
23
+ * and true is returned, else, they arent and false is returned.
24
+ *
25
+ * Bubble Sort isn't used for sorting because it times out for a input case
26
+ */
27
+ fun isAnagram (s : String , t : String ): Boolean {
28
+ if (s.length != t.length) return false
29
+ return s.sort() == t.sort()
30
+ }
31
+
32
+ /* *
33
+ * Method helper for sorting a string using bubble sort algorithm
34
+ */
35
+ fun bubbleSort (string : String ): String {
36
+ if (string.length < 2 ) return string
37
+ val arr = string.toCharArray()
38
+ var swapped = true
39
+ while (swapped) {
40
+ swapped = false
41
+ for (i in 1 .. string.lastIndex) {
42
+ if (arr[i] < arr[i- 1 ]) {
43
+ arr[i] = arr[i- 1 ].also { arr[i- 1 ] = arr[i] }
44
+ swapped = true
45
+ }
46
+ }
47
+ }
48
+ return arr.joinToString(separator = " " )
49
+ }
50
+
51
+ /* *
52
+ * String sort helper method using the inbuilt algorithm
53
+ */
54
+ private fun String.sort () = String (toCharArray().apply { sort() })
55
+
56
+ }
0 commit comments