话不多说,直接上代码。
- 第一个类是运行类Run.java
package com.imooc.strreverse;
import java.util.Scanner;
public class Run {
public Run() {
System.out.print("请输入一个字符串:");
Scanner sc = new Scanner(System.in);
String str = sc.next();
System.out.println();
String reversedStrByArray = new Reverse(str).reverseByArray();
System.out.println("对应反转字符串为[Array]:"+ reversedStrByArray);
String reversedStrByStack = new Reverse(str).reverseByStack();
System.out.println("对应反转字符串为[Stack]:"+ reversedStrByStack);
String reversedStrBySort = new Reverse(str).reverseBySort();
System.out.println("对应反转字符串为[逆序遍历]:"+ reversedStrBySort);
String reversedStrByBit = new Reverse(str).reverseByBit();
System.out.println("对应反转字符串为[位运算]:"+ reversedStrByBit);
String reversedStrByRecursive = new Reverse(str).reverseByRecursive(str);
System.out.println("对应反转字符串为[递归]:"+ reversedStrByRecursive);
}
public static void main(String[] args) {
new Run();
}
}
- 第二段代码是实现类Reverse.java
package com.imooc.strreverse;
import java.util.Stack;
public class Reverse {
String str = new String();
public Reverse(String str) {
this.str = str;
}
//用数组实现
public String reverseByArray() {
if(str == null str.length() == 0) {
return str;
}
int len = str.length();
char[] chArray = str.toCharArray();
for(int i= 0; i< len/2; i++) {
char temp;
temp = chArray[i];
chArray[i] = chArray[len- 1- i];
chArray[len- 1- i] = temp;
}
return new String(chArray);
}
//用栈实现
public String reverseByStack() {
if(str == null str.length() == 0) {
return str;
}
Stack<Character> strStack = new Stack<Character>();
char[] chArray = str.toCharArray();
for(Character ch: chArray) {
strStack.push(ch);
}
int len = str.length();
for(int i= 0; i< len; i++) {
chArray[i] = strStack.pop();
}
return new String(chArray);
}
//用逆序遍历实现
public String reverseBySort() {
if(str == null str.length() == 0) {
return str;
}
StringBuilder sb = new StringBuilder();
for(int i= str.length()- 1; i>= 0; i--) {
sb.append(str.charAt(i));
}
return sb.toString();
}
//用位运算实现
public String reverseByBit() {
if(str == null str.length() == 0) {
return str;
}
char[] chArray = str.toCharArray();
int len = str.length();
for(int i= 0; i< len/ 2; i++) {
chArray[i]^= chArray[len- 1- i];
chArray[len- 1- i]^= chArray[i];
chArray[i]^= chArray[len- 1- i];
}
return new String(chArray);
}
//用递归实现
public String reverseByRecursive(String str) {
if(str == null str.length() == 0) {
return str;
}
int len = str.length();
if(len == 1) {
return str;
} else {
return reverseByRecursive(str.substring(1))+ str.charAt(0);
}
}
}
点击查看更多内容
9人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦