344. Reverse String (Kotlin)
문제
Write a function that reverses a string. The input string is given as an array of characters s.
You must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
Constraints:
- 1 <= s.length <= 105
- s[i] is a printable ascii character.
풀이
나의 풀이법
class Solution {
fun reverseString(s: CharArray) = s.reverse()
}
다른 풀이법
풀이 1
fun reverseString(s: CharArray): Unit {
var p = 0
var q = s.size-1
while (p < q) {
val tempFront = s[p]
s[p] = s[q]
s[q] = tempFront
p++
q--
}
}
풀이 2
class Solution {
fun reverseString(s: CharArray): Unit {
var j = s.size-1
for(i in s.indices){
if(i<j){
var temp =s[i]
s[i] = s[j]
s[j] = temp
j--
}else{
break
}
}
}
}
'LeetCode > Kotlin | Easy' 카테고리의 다른 글
[LeetCode/Kotlin]Easy - 13. Roman to Integer (0) | 2024.05.09 |
---|---|
[LeetCode/Kotlin]Easy - 278. First Bad Version (0) | 2024.04.12 |
[LeetCode/Kotlin]Easy - 1. Two Sum (0) | 2023.10.13 |
[LeetCode/Kotlin]Easy - 506. Relative Ranks (0) | 2023.09.19 |
[LeetCode/Kotlin]Easy - 228. Summary Ranges (0) | 2023.09.19 |