<Algorithm> <go to achieve> left parenthesis complement - dual-stack method

 

 

Input: 1 + 2) * 33-44) * 555-666)))

Output: ((1 + 2) * ((33-44) * (555-666)))

Dual-stack method, as the name suggests, is to use two stacks to implement the algorithm. A data storage stack, a further saving in the stack operator.

Code implementation and comments:

package main

import "fmt"

/*
	左括号补全算法
*/

type stackString []string

func (s *stackString) Push(v string) {
	*s = append(*s, v)
}

func (s *stackString) Pop() string {
	l := len(*s)
	if l == 0 {
		return ""
	}
	ret := (*s)[l-1]
	*s = (*s)[:l-1]
	return ret
}

type stackByte []byte

func (s *stackByte) Push(v byte) {
	*s = append(*s, v)
}

func (s *stackByte) Pop() byte {
	l := len(*s)
	if l == 0 {
		return 0
	}
	ret := (*s)[l-1]
	*s = (*s)[:l-1]
	return ret
}

func isDigit(str string, i *int) *string {

	if str[*i] > '0' && str[*i] <= '9' {
		var retBytes []byte
		retBytes = append(retBytes, str[*i])
		for j := *i + 1; j < len(str); j++ {
			if str[j] > '0' && str[j] <= '9' {
				retBytes = append(retBytes, str[j])
			} else {
				*i = j - 1
				ret := string(retBytes)
				return &ret
			}
		}
	}
	return nil
}

func isOpeartor(b byte) bool {
	switch b {
	case '+', '-', '*', '/':
		return true
	default:
		return false
	}
}

func main() {
	str := "1+2)*33-44)*555-666)))"
	DATAS: = the make (stackString, 0)
	OPS: = the make (stackByte, 0) 
	for I: = 0; I <len (STR); I ++ {// the numbers and operators stack 
		IF RET: = isDigit (STR, & I); RET = nil {! 
			DATAS .push (RET *) 
		} isOpeartor the else IF (STR [I]) { 
			opS.Push (STR [I]) 
		} // remove the else {expression (numbers) and operators, combined and re-stack 
			d2: = dataS.Pop () 
			D1: = dataS.Pop () 
			OP: = opS.Pop () 
			exp: = "(" + D1 + String (OP) + D2 + ")" 
			dataS.Push (exp) 
		} 
	} 

	var exp String 
	for J: = 0; J <len (DATAS); J ++ { 
		exp + = DATAS [J] 
	} 

	fmt.Println (exp) 
}

  

  

Guess you like

Origin www.cnblogs.com/atinyant/p/12148801.html