14

leetcode_20

 4 years ago
source link: https://studygolang.com/articles/26282
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Golang:

思路:其实这题用栈的话很好解决,但Go里好像没有栈,我就用切片去实现了一个类似的栈,思路是,每当遇见 { [ ( 时,这些符号会进入切片(入栈),每当遇到 } ] ) 时,我们去查看切片尾端的符号是否是相对应的符号,不是则直接 return false ,是的话,切片会删除尾端的符号(出栈),在全部字符串处理完了以后,我们查看切片的长度,如果不为0,那么说明有符号没有配对成功,为0则说明成功了

注意:这里需要小心切片的长度问题,例:当我们去处理 "}()[]" 这个字符串时,遇见的第一个就是 } 符号,这时候查看切片尾端 res[len(res)-1]=='{' 可能会导致越界错误,因为此时res的长度为0。在这里我的处理方法是在每次判断时首先判断 len(res)!=0 ,如果为0,则直接可以 return false

Tips:这里我采用了Leetcode评论区里的一个方法,先判断字符串长度是否为偶数,不是则直接返回false,个人觉得这是程序员编程时敏锐度的一个体现,也希望以后我可以做到这样

func isValid(s string) bool {
    if len(s)%2!=0{
        return false
    }
    var res []byte
    for i:=0;i<len(s);i++{
        switch s[i] {
        case '}':
            if len(res)!=0&&res[len(res)-1]=='{' {
                res=res[:len(res)-1]
            }else {
                return false
            }
        case ']':
            if len(res)!=0&&res[len(res)-1]=='[' {
                res=res[:len(res)-1]
            }else {
                return false
            }
        case ')':
            if len(res)!=0&&res[len(res)-1]=='(' {
                res=res[:len(res)-1]
            }else {
                return false
            }
        default:
            res = append(res, s[i])
        }
    }
    if len(res)!=0{
        return false
    }else{
        return true
    }
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK