問題
原文
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:
12 Input: s = ["h","e","l","l","o"]Output: ["o","l","l","e","h"]Example 2:
12 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.
内容
文字列を反転させる関数を書いてください。入力される文字列は文字列sの配列で与えられます。
空間計算量O(1)、インプレイス処理で実装してください。
※正しくない可能性があります。
解答
解答1:
1 2 3 4 |
class Solution: def reverseString(self, s: List[str]) -> None: for i in range(len(s)//2): s[i], s[-(i+1)] = s[-(i+1)], s[i] |
two pointerの方が速い。
解答2:Python、two pointer
1 2 3 4 5 6 7 8 |
class Solution: def reverseString(self, s: List[str]) -> None: left = 0 right = len(s)-1 while left < right: s[left], s[right] = s[right], s[left] left += 1 right -= 1 |
解答3:Rust、reverse()
1 2 3 4 5 |
impl Solution { pub fn reverse_string(s: &mut Vec<char>) { s.reverse() } } |
Pythonでも同じように書ける。
解答4:Rust、iterator
1 2 3 4 5 6 7 8 9 10 11 12 13 |
impl Solution { pub fn reverse_string(s: &mut Vec<char>) { match s.len() { 0 => (), size => { (0..(size / 2)).into_iter().for_each(|beg| { let end = size -1 -beg; s.swap(beg, end); }); } }; } } |
補足・参考・感想
■補足
■参考
■感想
空間計算量の掴み方がわからない。
前:167. Two Sum II – Input Array Is Sorted
コメント