go語言實現棧和隊列
2021年4月6日
22:42
go語言實現棧和隊列主要用到append 和切片(用內置數組類型進行操作)
設數組var s []int
入棧:s=s.append(s,x) //x為添加的數據的類型
出棧:s=s[:len(s)-1]
設數組var q []int
入隊:q=q.append(q,x)
出隊:q=q[1:]
例題1.---------20. 有效的括號
給定一個只包括 '(',')','{','}','[',']' 的字符串 s ,判斷字符串是否有效。
有效字符串需滿足:
左括號必須用相同類型的右括號閉合。
左括號必須以正確的順序閉合。
示例 1:
輸入:s = "()"
輸出:true
示例 2:
輸入:s = "()[]{}"
輸出:true
示例 3:
輸入:s = "(]"
輸出:false
示例 4:
輸入:s = "([)]"
輸出:false
示例 5:
輸入:s = "{[]}"
輸出:true
提示:
1 <= s.length <= 104
s 僅由括號 '()[]{}' 組成
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/valid-parentheses
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
func isValid(s string)bool{
//奇數個字符一定不滿足題設
n:=len(s)
if n%2==1{
return false
}
pairs:=map[byte]byte{
')':'(',
']':'[',
'}':'{',
}
stack:=[]byte{}
//循環遍歷每個字符
for i:=0;i<n;i++{
//判斷是左括號還是右括號,
//是右括號,取map中對應左括號
if pairs[s[i]]>0{
//檢查是否棧頂元素(左括號)與當前符號(右括號)匹配,檢查棧是否為空
if len(stack)==0||stack[len(stack)-1]!=pairs[s[i]]{
return false
}
//出棧
stack=stack[:len(stack)-1]
}else{
//是左括號則入棧
stack=append(stack,s[i])
}
}
if len(stack)==0{
return true
}else{
return false
}
}
225. 用隊列實現棧
請你僅使用兩個隊列實現一個后入先出(LIFO)的棧,並支持普通隊列的全部四種操作(push、top、pop 和 empty)。
實現 MyStack 類:
void push(int x) 將元素 x 壓入棧頂。
int pop() 移除並返回棧頂元素。
int top() 返回棧頂元素。
boolean empty() 如果棧是空的,返回 true ;否則,返回 false 。
注意:
你只能使用隊列的基本操作 —— 也就是 push to back、peek/pop from front、size 和 is empty 這些操作。
你所使用的語言也許不支持隊列。 你可以使用 list (列表)或者 deque(雙端隊列)來模擬一個隊列 , 只要是標准的隊列操作即可。
示例:
輸入:
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
輸出:
[null, null, null, 2, 2, false]
解釋:
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // 返回 2
myStack.pop(); // 返回 2
myStack.empty(); // 返回 False
提示:
1 <= x <= 9
最多調用100 次 push、pop、top 和 empty
每次調用 pop 和 top 都保證棧不為空
進階:你能否實現每種操作的均攤時間復雜度為 O(1) 的棧?換句話說,執行 n 個操作的總時間復雜度 O(n) ,盡管其中某個操作可能需要比其他操作更長的時間。你可以使用兩個以上的隊列。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/implement-stack-using-queues
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
//雙隊列做法,主隊列q1存放的是棧內元素,q1出隊相當於出棧
//每次push加入新數至輔助隊列q2,主隊列存放之前棧內元素依次加入輔助隊列,再交換主隊列和輔助隊列(實現了主隊列q1一直保存的是棧內元素)
type MyStack struct {
q1 []int
q2 []int
}
/** Initialize your data structure here. */
func Constructor() (s MyStack) {
return
}
/** Push element x onto stack. */
func (s *MyStack) Push(x int) {
//入輔助隊列q2
s.q2=append(s.q2,x)
//如果主隊列不為空
for len(s.q1)>0{
//將主隊列q1中元素依次出隊,再入隊到輔助隊列q2
s.q2=append(s.q2,s.q1[0])
s.q1=s.q1[1:]
}
//交換兩個隊列
s.q1,s.q2=s.q2,s.q1
}
/** Removes the element on top of the stack and returns that element. */
func (s *MyStack) Pop() int {
//只用將主隊列出隊即可實現出棧操作
v:=s.q1[0]
s.q1=s.q1[1:]
return v
}
/** Get the top element. */
func (s *MyStack) Top() int {
return s.q1[0]
}
/** Returns whether the stack is empty. */
func (s *MyStack) Empty() bool {
if len(s.q1)==0{
return true
}else{
return false
}
}
/**
* Your MyStack object will be instantiated and called as such:
* obj := Constructor();
* obj.Push(x);
* param_2 := obj.Pop();
* param_3 := obj.Top();
* param_4 := obj.Empty();
*/
