01.05.2024
2000. Reverse Prefix of Word easy
blog post
Join me on Telegram
https://t.me/leetcode_daily_unstoppable/589
Problem TLDR
Reverse [..ch]
prefix in string #easy
Intuition
First find the position, then reverse the prefix.
Approach
Can you make the code shorter? (Don’t do this in the interview, however, we skipped optimized case of not found index.)
Complexity
Time complexity:
O(n)Space complexity:
O(n)
Code
fun reversePrefix(word: String, ch: Char) = String(
word.toCharArray().apply { reverse(0, indexOf(ch) + 1) }
)
pub fn reverse_prefix(mut word: String, ch: char) -> String {
let i = word.find(ch).unwrap_or(0) + 1;
word[..i].chars().rev().chain(word[i..].chars()).collect()
}