iT邦幫忙

2021 iThome 鐵人賽

DAY 16
0

大家好,我是毛毛。ヾ(´∀ ˋ)ノ
廢話不多說開始今天的解題Day~


344. Reverse String

Question

Write a function that reverses a string. The input string is given as an array of characters s.


Example

Example1

Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

Example2

Input: s = ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]

Constraints

  • 1 <= s.length <= 10^5
  • s[i] is a printable ascii character.

解題

題目

首先先簡單的翻譯一下題目
給一個Strings,把這個String用in-place的方式做reverse。

Think

作法大致上是這樣

  • lowhigh兩個index指向String的頭跟尾,然後互換就這樣XD。

Code

Python

class Solution:
    def reverseString(self, s: List[str]) -> None:
        """
        Do not return anything, modify s in-place instead.
        """
        low = 0
        high = len(s)-1
        
        while low<=high:
            s[low], s[high] = s[high], s[low]
            low += 1
            high -= 1

C

void reverseString(char* s, int sSize){
    int low = 0;
    int high = sSize-1;
    int tmp;
    
    while (low<=high){
        tmp = s[low];
        s[low] = s[high];
        s[high] = tmp;
        low++;
        high--; 
    }
}

Result

  • Python

  • C

大家明天見/images/emoticon/emoticon29.gif


上一篇
Day 15 - Excel Sheet Column Number
下一篇
Day 17 - Remove Duplicates from Sorted List
系列文
30天 Leetcode解題之路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言