Welcome to Subscribe On Youtube
3794. Reverse String Prefix
Description
You are given a string s and an integer k.
Reverse the first k characters of s and return the resulting string.
Example 1:
Input: s = "abcd", k = 2
Output: "bacd"
Explanation:
The first k = 2 characters "ab" are reversed to "ba". The final resulting string is "bacd".
Example 2:
Input: s = "xyz", k = 3
Output: "zyx"
Explanation:
The first k = 3 characters "xyz" are reversed to "zyx". The final resulting string is "zyx".
Example 3:
Input: s = "hey", k = 1
Output: "hey"
Explanation:
The first k = 1 character "h" remains unchanged on reversal. The final resulting string is "hey".
Constraints:
1 <= s.length <= 100sconsists of lowercase English letters.1 <= k <= s.length
Solutions
Solution 1: Simulation
We reverse the first $k$ characters of the string according to the problem description, and then concatenate them with the remaining characters.
The time complexity is $O(n)$ and the space complexity is $O(n)$, where $n$ is the length of the string.
-
class Solution { public String reversePrefix(String s, int k) { StringBuilder sb = new StringBuilder(s.substring(0, k)); return sb.reverse().toString() + s.substring(k); } } -
class Solution { public: string reversePrefix(string s, int k) { string t = s.substr(0, k); reverse(t.begin(), t.end()); return t + s.substr(k); } }; -
class Solution: def reversePrefix(self, s: str, k: int) -> str: return s[:k][::-1] + s[k:] -
func reversePrefix(s string, k int) string { t := []byte(s[:k]) slices.Reverse(t) return string(t) + s[k:] } -
function reversePrefix(s: string, k: number): string { return s.slice(0, k).split('').reverse().join('') + s.slice(k); }