Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use leetcode to realize inverse Polish style in golang

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

今天就跟大家聊聊有关golang中怎么利用leetcode实现逆波兰式,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

根据逆波兰表示法,求表达式的值。

有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。

说明:

整数除法只保留整数部分。

给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。

示例 1:

输入: ["2", "1", "+", "3", "*"]输出: 9解释: ((2 + 1) * 3) = 9

示例 2:

输入: ["4", "13", "5", "/", "+"]输出: 6解释: (4 + (13 / 5)) = 6

示例 3:

输入: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]输出: 22解释: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5= ((10 * (6 / (12 * -11))) + 17) + 5= ((10 * (6 / -132)) + 17) + 5= ((10 * 0) + 17) + 5= (0 + 17) + 5= 17 + 5= 22

解题思路:

本题很简单,理解逆波兰式就ok

逆波兰式求解原理:

1,从左往右扫描token

2,如果式操作数,入栈

3,如果是操作符,弹出两个操作数

4,计算结果,将结果入栈

5,扫描完token,栈中,剩下结果,结果出栈

import "strconv"

func evalRPN(tokens []string) int { var s stack for i := 0; i < len(tokens); i++ { if !isOperator(tokens[i]) { s.Push(tokens[i]) } else { op2 := s.Pop() op1 := s.Pop() res := eval(op1, op2, tokens[i]) s.Push(fmt.Sprint(res)) } } r := s.Pop() rv, _ := strconv.ParseInt(r, 10, 64) return int(rv)

}

func eval(op1 string, op2 string, token string) int64 { o1, _ := strconv.ParseInt(op1, 10, 64) o2, _ := strconv.ParseInt(op2, 10, 64) switch token { case "+": return o1 + o2 case "-": return o1 - o2 case "*": return o1 * o2 case "/": return o1 / o2 } return 0}

func isOperator(token string) bool { return token == "+" || token == "-" || token == "*" || token == "/"}

type stack struct { data []string}

func (s *stack) Push(str string) { s.data = append(s.data, str)}

func (s *stack) Pop() string { if len(s.data) < 1 { return "" } str := s.data[len(s.data)-1] s.data = s.data[:len(s.data)-1] return str}看完上述内容,你们对golang中怎么利用leetcode实现逆波兰式有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report