Topic:

Given a only include a ‘(‘,’) ‘, ‘{‘,’} ‘, ‘/’, ‘ ‘the string s, determine whether a string is effective.

A valid string must meet the following requirements:

The opening parenthesis must be closed with a closing parenthesis of the same type. The opening brackets must be closed in the correct order.

  • Source: LeetCode
  • Link: leetcode-cn.com/problems/va…

Their thinking

Open bracket is pushed on the stack. Close bracket is compared to the close bracket mapped in the map at the top of the stack. If it matches, the stack is out.

func isValid(s string) bool {
    m := map[byte]byte{'{':'} '.'[':'] '.'(':') '}
	var stack []byte
	for i := 0; i < len(s); i++ {
		if _, ok := m[s[i]]; ok {
			stack = append(stack,s[i])
		}else{
			if len(stack)>0 && m[stack[len(stack)- 1]] ==s[i]{
				stack = stack[:len(stack)- 1]}else{
				return false}}}return len(stack) == 0
}
Copy the code

Idea 2

For a given string s, if be in parentheses, then put them away to (replace null), and, in turn, determine whether there are pairs of parentheses, the elimination, until no brackets appear in pairs, finally to determine whether a string s is empty, empty, all braces are correct, in pairs have been elimination, returns true, If the value is not empty, there are illegal parentheses. Return false.

import (
	"fmt"
	"strings"
)

func main(a) {
	re := isValid("([]])")
	fmt.Println(re)
}
func isValid(s string) bool {
	for {
		find1 := strings.Contains(s, "()")
		find2 := strings.Contains(s, "[]")
		find3 := strings.Contains(s, "{}")
		if find1 || find2 || find3 {
			s = strings.Replace(s,"()"."".- 1)
			s = strings.Replace(s,"[]"."".- 1)
			s = strings.Replace(s,"{}"."".- 1)}else{
			break}}return len(s)==0
}
Copy the code