zoukankan      html  css  js  c++  java
  • 用栈实现反转字符串输入问题

    给定一个字符串,逐个翻转字符串中的每个单词。例如,输入: "the sky is blue",输出: "blue is sky the"。

    package main
    
    import (
        "fmt"
        "strings"
    )
    
    type SStack struct {
        elems []string
    }
    
    func (this SStack) Is_empty() bool {
        return len(this.elems) == 0
    }
    
    func (this SStack) Top() string {
        if this.Is_empty() {
            panic("in SStack.top")
        }
        return this.elems[len(this.elems)-1]
    }
    
    func (this *SStack) Push(elem string) {
        this.elems = append(this.elems, elem)
    }
    
    func (this *SStack) Pop() string {
        if this.Is_empty() {
            panic("in SStack.pop")
        }
        elem := this.elems[len(this.elems)-1]
        this.elems = this.elems[:len(this.elems)-1]
        return elem
    }
    
    func main() {
        s := SStack{}
        str := "the sky is blue"
        ss := strings.Split(str, " ")
    
        for _, i := range ss {
            s.Push(i)
        }
        var resultStr string
        for !s.Is_empty() {
            resultStr += s.Pop()
            resultStr += " "
        }
        resultStr = strings.TrimSpace(resultStr)
        fmt.Println(resultStr)
    }
    人生就是要不断折腾
  • 相关阅读:
    2020/5/8
    2020/5/8
    2020/5/6
    2020/4/30
    2020/4/29
    2020/4/28
    2020/4/27
    KMP算法详解
    博客搬家声明
    洛谷P2831 NOIP2016 愤怒的小鸟
  • 原文地址:https://www.cnblogs.com/xiangxiaolin/p/13590533.html
Copyright © 2011-2022 走看看