Re: [閒聊] 每日leetcode已回收

看板Marginalman作者 (虛構史學家)時間1年前 (2024/07/11 16:22), 編輯推噓1(100)
留言1則, 1人參與, 1年前最新討論串474/1550 (看更多)
※ 引述《oin1104 (是oin的說)》之銘言: : 題目: : 給你字串 : 裡面有()跟其他字母 : 每次遇到()都要翻轉中間所有的東西 : 然後()就消失 : 回傳他給的字串翻轉後的結果 思路: 用stack 但我沒怎麼遇過 害我我去查了 幸好Rust多半都有push pop可以用 步驟 1. 沒遇到括號就放進str 2. 遇到左括號先把目前的str放進stack 3. 遇到右括號代表這一段結束, 把目前存str的反轉, 把stack倒出來,把反轉的放在stack的str後面, 然後因為不用再處理,所以全部放回str,重覆到結束 Code: impl Solution { pub fn reverse_parentheses(s: String) -> String { let mut stack = Vec::new(); let mut cur_str = String::new(); for ch in s.chars() { if ch == '(' { stack.push(cur_str); cur_str = String::new(); } else if ch == ')' { cur_str = cur_str.chars().rev().collect(); if let Some(mut top) = stack.pop() { top.push_str(&cur_str); cur_str = top; } } else { cur_str.push(ch); } } cur_str } } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.32.48.170 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1720686129.A.F48.html

07/11 16:39, 1年前 , 1F
大師
07/11 16:39, 1F
文章代碼(AID): #1cZvOnz8 (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1cZvOnz8 (Marginalman)