# 344. Valid Parentheses ### Background problem: https://leetcode.com/problems/reverse-string/description/ 寫個function將字串排序顛倒。Input String將會以個別Array: s 的方式給出。 任何的修改都只能直接修改字串並只能使用O(1)的額外記憶體。 ### Code ```python3= class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ ## 設定兩個指針,一個在array起始,一個在最後 ## right指針往前,left指針往後 right, left = 0, len(s)-1 ## 因為前後互換,所以只需要兩個指針相鄰即可結束 ## 如果是Array有單數個,最中間也不用做任何動作 (所以不用right <= left) ## 如果Array是雙數個,兩個指針相鄰即可結束 while right < left: s[left], s[right] = s[right], s[left] ## 這樣寫就不用temp 來暫存要被替換的值 # temp = "" # temp = s[left] # s[left] = s[right] # s[right] = temp ## 將兩根指針各往中間推一個 right +=1 left -=1 ``` ### Explanation 使用雙指針方式,詳細如code中的解釋 ###### tags: `leetcode` `easy` `two-pointer`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up