本方法取自牛客网 HJ12 字符串反转题解。
1.字符串反转
输入一行字符串,将其反转,输出为反转后的字符串。
这里使用栈的数据结构处理。
2.反转方法
栈的数据结构特点为先进后出,所以可以将字符串逐个输入到栈中,然后输出,即可得到反转的字符串。
public static String reverse(String str){
//使用栈先进后出
Stack stack = new Stack();
String tem = "";
for (int i = 0; i <= str.trim().length()-1; i++) {
stack.push(str.charAt(i));
}
while (!stack.empty()){
Object pop = stack.pop();
tem += pop.toString();
}
return tem;
}
3.测试
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNext()) { // 注意 while 处理多个 case
String next = in.nextLine();
System.out.println(reverse(next));
}
}