//Go funcisValid(s string)bool { iflen(s)%2 == 1 { returnfalse } forlen(s) != 0 { temp := s s = strings.Replace(s, "()", "", -1) s = strings.Replace(s, "[]", "", -1) s = strings.Replace(s, "{}", "", -1)
if s == temp { returnfalse } }
returntrue }
执行结果:
1 2 3 4 5 6 7
leetcode-cn执行: 执行用时:4 ms, 在所有 Go 提交中击败了6.50%的用户 内存消耗:7.1 MB, 在所有 Go 提交中击败了5.26%的用户
leetcode执行: Runtime: 4 ms, faster than 5.19% of Go online submissions for Valid Parentheses. Memory Usage: 7 MB, less than 7.32% of Go online submissions for Valid Parentheses.
//Go funcisValid(s string)bool { //考虑空字符串的特殊情况 if s == "" { returntrue } //定义一个栈 stack := make([]int32, len(s)) length := 0 //判断括号是否匹配 for _,v := range s { if v == '(' || v == '[' || v == '{' { //左括号,入栈 stack[length] = v length++ } else { //右括号,比较栈顶,匹配则移除,不匹配就返回false if length == 0 { returnfalse } if (v == ')' && stack[length-1] == '(') || (v == ']' && stack[length-1] == '[') || (v == '}' && stack[length-1] == '{') { length-- } else { returnfalse } } }
return length == 0 }
执行结果:
1 2 3 4 5 6 7
leetcode-cn执行: 执行用时:0 ms, 在所有 Go 提交中击败了100.00%的用户 内存消耗:2 MB, 在所有 Go 提交中击败了72.86%的用户
leetcode执行: Runtime: 0 ms, faster than 100.00% of Go online submissions for Valid Parentheses. Memory Usage: 2 MB, less than 98.88% of Go online submissions for Valid Parentheses.