Leetcode每日一题-1047,224,232

Daily

leetcode

1047.删除字符串中所有相邻重复项

描述

给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。

在 S 上反复执行重复项删除操作,直到无法继续删除。

在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。

示例

输入:"abbaca"
输出:"ca"
解释:
例如,在 "abbaca" 中,我们可以删除 "bb" 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。之后我们得到字符串 "aaca",其中又只有 "aa" 可以执行重复项删除操作,所以最后的字符串为 "ca"。

分析

利用栈来解决,新进元素和栈顶元素比较,若相同,则栈顶出栈。

注意临界判断。

代码

func removeDuplicates(S string) string {
    // 切片模拟栈
	stack := make([]byte, len(S))
    // 栈深
	size := 0
	for i := range S {
		if size > 0 && stack[size-1] == S[i] {
             // size--表示出栈
			size--
		} else {
            // 进栈
			stack[size] = S[i]
			size++
		}
	}
    // 将栈转为字符串
	return string(stack[:size])
}

224. 基本计算器

描述

实现一个基本的计算器来计算一个简单的字符串表达式 s 的值。

示例

示例 1:

输入:s = "1 + 1"
输出:2
示例 2:

输入:s = " 2-1 + 2 "
输出:3
示例 3:

输入:s = "(1+(4+5+2)-3)+(6+8)"
输出:23

提示

  • 1 <= s.length <= 3 * 105
  • s 由数字、'+''-''('')'、和 ' ' 组成
  • s 表示一个有效的表达式

分析

由于只有+,-运算,所以可以想到去括号的形式

设置一个标记为sign,sign表示当前的运算应该是+还是-

有一个栈opt维护小括号,当存在小括号的时候,小括号里面的运算符依赖于小括号前的sign

代码

方式一:通过switch

func calculate(s string) (ret int) {
	// 决定当前是+还是-
	sign := 1
	n := len(s)
	// 操作数栈 一开始是+的
	opt := make([]int, n)
	opt[0] = 1
	// top为栈顶标记
	top := 0
	for i := 0; i < n; {
		switch s[i] {
		case ' ':
			i++
		case '+':
			sign = opt[top]
			i++
		case '-':
			sign = -opt[top]
			i++
		case '(':
			// 判断括号前的符号
			top++
			opt[top] = sign
            i++
		case ')':
			top--
            i++
		default:
			// 数值直接运算, 注意数值可能有多位,循环取值
			num := 0
			for ; i <n && s[i] <= '9' && s[i] >= '0'; i++ {
				num = num * 10 + int(s[i]) - '0'
			}
			ret += num*sign
		}
	}
	return
}

方式二:不使用switch,使用map记录操作

func calculate(s string) (ret int) {
	// 决定当前是+还是-
	sign := 1
	n := len(s)
	// 操作数栈 一开始是+的
	opt := make([]int, n)
	opt[0] = 1
	// top为栈顶标记
	top := 0
	i := 0
	tagMap := map[uint8]func(){
		' ': func() {
		},
		'+': func() {
			sign = opt[top]
		},
        '-': func() {
			sign = -opt[top]
		},
		'(': func() {
			// 判断括号前的符号
			top++
			opt[top] = sign
		},
		')': func() {
			top--
		},
	}
	for i < n {
		do, ok := tagMap[s[i]]
		// 数值直接运算, 注意数值可能有多位,循环取值
		if ok {
			do()
			i++
		} else {
			num := 0
			for ; i < n && s[i] <= '9' && s[i] >= '0'; i++ {
				// v := int(s[i]) - '0'
				num = num*10 + int(s[i]) - '0'
			}
			ret += num * sign
		}
	}
	return
}

232. 用栈实现队列

描述

请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):

实现 MyQueue 类:

void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false

说明

你只能使用标准的栈操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。

进阶

  • 你能否实现每个操作均摊时间复杂度为 O(1) 的队列?换句话说,执行 n 个操作的总时间复杂度为 O(n) ,即使其中一个操作可能花费较长时间。

示例

输入:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 1, 1, false]

解释:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

提示

1 <= x <= 9
最多调用 100 次 push、pop、peek 和 empty
假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)

分析

go语言没有自己的stack,使用切片+size简单实现stack

两个栈实现队列

代码

// 栈实现
type stack struct {
	arr  []int
	size int
}

// 构建栈
func newStack() stack {
	return stack{make([]int, 10), 0}
}

// 栈push
func (this *stack) stackPush(x int) {
	ensureCapacity(this)
	this.arr[this.size] = x
	this.size++
}

// 栈pop
func (this *stack) stackPop() int {
	ret := this.arr[this.size-1]
	this.size--
	return ret
}

// 栈peek
func (this *stack) stackPeek() int {
	return this.arr[this.size-1]
}

// 栈空判断
func (this *stack) isEmpty() bool {
	if this.size == 0 {
		return true
	}
	return false
}

// 栈扩容,2倍扩容
func ensureCapacity(stack *stack){
	if stack.size == len(stack.arr) {
		tmp := stack.arr
		stack.arr = make([]int, len(tmp) << 1)
		for i, v := range tmp {
			stack.arr[i] = v
		}
	}
}

// 以下是基于栈的队列实现
type MyQueue struct {
	stack1 stack
	stack2 stack
}

/** Initialize your data structure here. */
func Constructor() MyQueue {
	return MyQueue{newStack(), newStack()}
}

// 来回倒腾,时间复杂度O(n2)
/** Push element x to the back of queue. */
func (this *MyQueue) Push(x int) {
	for !this.stack1.isEmpty() {
		this.stack2.stackPush(this.stack1.stackPop())
	}
	this.stack1.stackPush(x)
	for !this.stack2.isEmpty() {
		this.stack1.stackPush(this.stack2.stackPop())
	}
}

/** Removes the element from in front of queue and returns that element. */
func (this *MyQueue) Pop() int {
	return this.stack1.stackPop()
}

/** Get the front element. */
func (this *MyQueue) Peek() int {
	return this.stack1.stackPeek()
}

/** Returns whether the queue is empty. */
func (this *MyQueue) Empty() bool {
	return this.stack1.isEmpty()
}
posted @ 2021-03-10 20:45  blog_zhangtong  阅读(73)  评论(0)    收藏  举报