反轉字串但單詞不反轉
package org.lza;
//import java.util.Stack;
/*
* Given an input string, reverse the string word by word.
* For example,
* Given s = "the sky is blue",
* return "blue is sky the".
*/
/*
* 思路:首先 看到題目中只是單詞被反序 單詞內部沒有反序 想到反序可以用棧來實現
*/
public class ReverseString {
public static void main(String[] args) {
String s = "the sky is blue";
String reversStr = Reverse(s);
System.out.println(reversStr);
}
public static String Reverse(String s) {
// 建立一個空棧
int length = s.length();
Stack stack = new Stack();
char[] str = s.toCharArray();
// char[] strRs=new char[length];
StringBuffer strRs = new StringBuffer();
for (char ch : str) {
stack.push(ch);// 入棧
}
Stack stackTemp = new Stack();
int j = -1;
for (int i = 0; i < length; i++) {
if (stack.isEmpty())
break;
char ch = (char) stack.pop();
if (ch != ' ') { // 將單詞字母入棧
stackTemp.push(ch);
if(!stack.isEmpty())
continue;
}
if (!stackTemp.isEmpty()) {// 碰到空字元或者棧底則反轉單詞
while(!stackTemp.isEmpty())
// strRs[n]=(char)stackTemp.pop();
strRs.append(stackTemp.pop());
j = i;
}
if(ch==' ')
strRs.append(ch);
}
return strRs.toString();
}
}
class Stack {
private final int LEN = 10;// 初始棧大小
private int top;// 棧頂指標
private Object[] elements;// 資料元素陣列
public Stack() { // 初始化棧
top = -1;
elements = new Object[LEN];
}
/*
* 函式名:isEmpty()
* @return:棧為空則返回true,否則返回false
*/
public boolean isEmpty() {
return top < 0;
}
/*
* 函式名:public void push(Object e)
* 函式功能:將元素插入棧中
* @param Object e:要進棧的元素
* @return :無
*/
public void push(Object e){
if(elements.length+1>=LEN){
//擴充儲存空間
expandStack();
}
elements[++top]=e;
}
private void expandStack(){
Object[] temp=new Object[elements.length*2];
for(int i=0;i<elements.length;i++){
temp[i]=elements[i];
}
elements=temp;
}
public int getSize(){
return top+1;
}
public Object pop(){
if(getSize()<1){
System.out.println("空棧!");
return null;
}
Object e=elements[top];
elements[top--]=null;//釋放記憶體
return e;
}
}