翻转单词顺序列

翻转单词顺序列

http://www.nowcoder.com/questionTerminal/3194a4f4cf814f63919d0790578d51f3

题目抽象:给定一个首尾可能带空格的字符串,请让你翻转该字符串。首尾不能有多余空格。如果全部是空格,请返回原字符串。

  1. 实现拆分单词的操作。一个单词为:从不是空格的字符开始到是空格的前一个字符结束,即为一个单词。
  2. 借助栈来存放分离出来的单词
public static String ReverseSentence(String str) {
    if (str == null || str.length() < 2) {
        return str;
    }
    StringBuilder tem = new StringBuilder();
    Deque<String> stack = new LinkedList<>();
    String result = "";
    for (int i = 0; i < str.length(); i++) {
        if (str.charAt(i) != ' ') {
            tem.append(str.charAt(i));
        }
        if (str.charAt(i) == ' ' && tem.length() != 0) {
            stack.push(tem.toString());
            tem.delete(0, tem.length());
        }
    }
    if (tem.length() != 0) {
        stack.push(tem.toString());
    }
    if (stack.isEmpty()) {
        return str;
    }
    result = result + stack.pop();
    while (!stack.isEmpty()) {
        result = result + " " + stack.pop();
    }
    return result;
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务