本文共 1858 字,大约阅读时间需要 6 分钟。
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。注意空字符串可被认为是有效字符串。
示例 1: 输入: "()" 输出: true 示例 2: 输入: "()[]{}" 输出: true 示例 3: 输入: "(]" 输出: false 示例 4: 输入: "([)]" 输出: false 示例 5: 输入: "{[]}" 输出: true
拿到这道题,首先是想到要用什么样的数据结构来模拟这个过程。匹配的时候需要和相近的最后一个元素来做匹配,有点先进后出的味道,所以先考虑使用栈来实现。
而除了我们自定义数据结构stack外,不同的编程语言有对应的可以用来模拟stack的原生数据结构。如PHP中的万金油:array,Python中的list(列表),这次我们还是使用Golang来实现算法,所以考虑用slice来模拟出栈和进栈。
大方向确定后也要考虑一些边界问题,例如当时空字符串的时候,也是有效的。
整理思路如下:
1.获取s字符串的长度。2.判断长度是否非空,如果为空,则返回true。3.判断长度是否为偶数,如果不是偶数,那么肯定不能成对匹配,总会剩下一个“老光棍”字符,就是无效的。4.循环匹配,如果当前循环的字符是“{”、“[”、“(”之一,则入栈到stack里面。然后后面的如果是成对的另外一个字符,那就可以把之前栈顶的那个元素出栈,有点类似于消消乐的感觉,就近匹配,就近销毁。Talk is cheap, show you my codes:
package main import "fmt" func isValid(s string) bool { my_dick := map[byte] byte {']':'[', ')':'(', '}': '{'} // The single char's type is byte, pay attention please. s_len := len(s) // Get the length of the string s var stack []byte // Just use a empty slice to mock the stack if s_len == 0 { return true } if s_len % 2 != 0 { // If the length of the string s is not even number, it could not be valid return false } for i := 0; i < s_len; i++ { if s[i] == '[' || s[i] == '{' || s[i] == '(' { // First char should be these stack = append(stack, s[i]) // push it to slice } else if len(stack) == 0 { // Once empty slice just pass to next item. return false } else { if my_dick[s[i]] == stack[len(stack)-1] { stack = stack[:len(stack) -1] // pop the last item } else { return false } } } if len(stack) == 0 { return true } else { return false } } func main() { result := isValid("{[}}") fmt.Println(result) }
简单的问题也可以思考很多,这大概就是编程的魅力吧。
转载地址:http://dusuz.baihongyu.com/