题目
输入一个字符串,其中包含 [](){} 六种括号,请你判断这个字符串组成的括号是否合法。
题目示例
Input: "()[]{}"
Output: true
Input: "([)]"
Output: false
Input: "{[]}"
Output: true
第一种实现方式
解题思路
利用堆栈数据结构的特性:
1、先入后出,后入先出。
2、除头尾节点之外,每个元素有一个前驱,一个后继。
利用堆栈解题的时间复杂度 O(n)
Golang解题代码
import (
"container/list"
"fmt"
"testing"
)
func TestStrValid(t *testing.T) {
str:="[([{}])]"
fmt.Printf("str:%v, res: %v;\n ",str,is_valid(str))
str="[]{}()"
fmt.Printf("str:%v, res: %v;\n ",str,is_valid(str))
str="[]{})("
fmt.Printf("str:%v, res: %v;\n ",str,is_valid(str))
}
func is_valid(str string) bool{
strLen:=len(str)
//判断数据合法性,基本的校验
if strLen == 0 {
return true
}
if strLen % 2 == 1 {
return false
}
//利用go里面的list 模拟stack 主要用到front 、remove 方法来模拟堆栈的POP、Push方法
stack := list.New()
pairsMap:= map[byte]byte{')':'(',']':'[','}':'{'}
for i:=0 ;i< strLen ;i++ {
value:=str[i]
//碰见左边的入栈,右边则不入栈,并获取上一个元素与该元素匹配是否正确
if pairsMap[value] == 0 {
//入栈
stack.PushFront(value)
}else{
//出栈、通过右边获取map中的值,与list front相对比
if stack.Len()==0 || stack.Front().Value != pairsMap[value]{
return false
}
//fmt.Printf("front value:%v; value:%v \n",stack.Front().Value,pairsMap[value])
//匹配成功则删除、左右删除,知道最后
stack.Remove(stack.Front())
}
}
//最后判断list的len大小
return stack.Len()==0
}
结果验证

代码剖析&总结
示例字符串:
"()[]{}"
思路:左边的入栈、右边不入栈、获取栈上个元素、判断左右是否成对,一旦成对,则删除
按照上述思路,写伪代码解题:
首先需要定义map,map的用途有两个,第一是:判断是左边还是右边,第二是判断是否成对
此外定义栈,这里用go的list模拟stact
stack := list.New()
Map存储结构k-v,存储内容如下
')':'('
']':'['
'}':'{'
第一次入栈:( //遍历上述字符串,判断该key是否存在,不存在,则是左边,左边的入栈stack
第二次入栈: ) //右边不入栈、根据右边的key,获取map的value,并获取栈stack的数据与之匹配,看是否成对,如不成对,则直接返回false,如成对,则可删除该对符号
最后,直接判断栈的大小,如果等于零的,则说明该字符串全部成对
第二种实现方式
解题思路
判断字符串括号合法性,首先该字符串是偶数,另外字符串首部和尾部是必然是成对的,利用该思路,循环首先从首位向中间对比。
利用该思路解题的时间复杂度 O(n/2)
Golang解题代码
func is_valid_v1(str string) bool{
strLen:=len(str)
//判断数据合法性,基本的校验
if strLen == 0 {
return true
}
if strLen % 2 == 1 {
return false
}
//判断标识位从根据右边获取左边的
pairsMap:= map[byte]byte{')':'(',']':'[','}':'{'}
//判断标识位从根据左边边获取右边的
//pairsMap= map[byte]byte{'(':')','[':']','{':'}'}
for i:=0 ;i< strLen/2 ;i++ {
indexValue:=str[i]
lastValue:=str[strLen-1-i]
//因map是右边获取左边,则用lastValue 对比indexValue
if pairsMap[lastValue]!=indexValue {
//如果上述用pairsMap= map[byte]byte{'(':')','[':']','{':'}'} 这判断用indexValue获取对比lastValue
//if pairsMap[indexValue]!=lastValue{
return false
}
}
return true
}
















