package com.zmz.algorithm;

import java.util.Stack;

/**
 * @author 张明泽
 * Create by 2022/5/22 19:06
 * 颠倒字符串中的单词
 * LeetCode-151
 */
public class TurnOverWord {
    public static void main(String[] args) {
        String s = "  hello  world  ";
        System.out.println(turnWordStack(s));
    }

    /**
     * 翻转数组
     * 分割以空格(" ") -> ["zhang","ming","ze"]
     * 分割以("") -> ["z","h","a","n","g"...]
     * isEmpty()可以过滤掉空数组
     */
    public static String turnWord(String s) {
        s = s.trim();
        String[] word = s.split(" ");
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = word.length - 1; i >= 0 ; i--) {
            if(!word[i].isEmpty()) {
                stringBuffer.append(word[i]);
                if (i != 0) {
                    stringBuffer.append(" ");
                }
            }
        }
        return stringBuffer.toString();
    }

    /**
     * 利用栈
     */
    public static String turnWordStack(String s) {
        s = s.trim();
        Stack<String> stack = new Stack<>();
        String[] words = s.split(" ");
        for (String word : words) {
            if (!word.isEmpty()) {
                stack.push(word);
            }
        }
        StringBuffer stringBuffer = new StringBuffer();
        while(!stack.isEmpty()) {
            stringBuffer.append(stack.pop());
            if(!stack.isEmpty()) {
                stringBuffer.append(" ");
            }
        }
        return stringBuffer.toString();
    }
}
最后修改:2022 年 05 月 27 日 07 : 09 AM
赏杯咖啡喝 谢谢您~