Skip to content

Commit 99869e1

Browse files
committed
2 parents d7383e0 + 2195263 commit 99869e1

File tree

2 files changed

+90
-0
lines changed

2 files changed

+90
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package practice
2+
3+
/**
4+
* @author EfeDaniel
5+
* Link: https://leetcode.com/problems/sort-colors
6+
* Progress: Done
7+
*/
8+
object SortColors {
9+
10+
/**
11+
* Solution Method. Just applies bubble sort on the input array
12+
*/
13+
fun sortColors(nums: IntArray) {
14+
nums.bubbleSort()
15+
}
16+
17+
/**
18+
* Extension function to bubble sort an Int Array
19+
*/
20+
fun IntArray.bubbleSort() {
21+
if (size < 2) return
22+
var swapped = true
23+
while (swapped) {
24+
swapped = false
25+
for (i in 1..lastIndex) {
26+
if (this[i] < this[i-1]) {
27+
this[i] = this[i-1].also { this[i-1] = this[i] }
28+
swapped = true
29+
}
30+
}
31+
}
32+
}
33+
34+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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

Comments
 (0)