package com.linux.util;
import java.util.Stack;
public class StringReverseOrder {
public static void main(String[] args) {
// reverOrder1();
// reverOrder2();
// reverOrder3();
// reverOrder4();
// System.out.println(reverseOrder5("abcdefg"));
primeNumber();
}
public static void reverOrder1() {
//反向迭代法
String string = "abcdefg";
StringBuilder builder = new StringBuilder();
int length = string.length();
for(int i=0;i<length;i++) {
builder.append(string.charAt(length-1-i));
}
System.out.println(builder.toString());
}
public static void reverOrder2() {
//二分法,前后同时赋值,这种方式比较快
String string = "abcdefg";
int length = string.length();
char[] cs = string.toCharArray();
for(int i=0;i<length/2;i++) {
cs[i] = string.charAt(length-1-i);
cs[length-1-i] = string.charAt(i);
}
System.out.println(new String(cs));
}
public static void reverOrder3() {
//入栈法,栈具有后进先出功能,这种方式循环次数太多
String string = "abcdefg";
Stack<Character> stack = new Stack<Character>();
char[] cs = string.toCharArray();
for(Character c : cs) {
stack.push(c);
}
//栈弹出元素后,栈会逐渐减小
for(int i=0;i<string.length();i++) {
cs[i] = stack.pop();
}
System.out.println(new String(cs));
}
public static void reverOrder4() {
//使用异或进行交换
char a,b;
a = 'A';
b = 'B';
a ^= b;
b ^= a;
a ^= b;
System.out.println(a +" = "+ b);
int c,d;
c = 1;
d = 2;
c = c ^ d;//与c ^= d 等同
d = c ^ d;
c = c ^ d;
System.out.println(c +" # "+ d);
String string = "abcdefg";
int length = string.length()-1;
char[] cs = string.toCharArray();
for(int i=0;i<length;i++,length--) {
cs[i] ^= cs[length];
cs[length] ^= cs[i];
cs[i] ^= cs[length];
}
System.out.println(new String(cs));
}
public static String reverseOrder5(String string) {
//递归的方式,通过将字符串逐一读取,这种方式消耗内存较大
int length = string.length();
if(length == 1) {
System.out.println(string);
return string;
}else {
String string2 = reverseOrder5(string.substring(1))+string.charAt(0);
System.out.println(string2);
return string2;
}
}
public static void primeNumber() {
//质数查找
int[] in = {12,31,39,56};
for(int i=0;i<in.length;i++) {
int c = 0;
int integer = in[i];
for(int j=2;j<integer;j++) {
if(integer % j != 0) {
c++;
}
}
if(c == (integer-2)) {
System.out.println(integer +"是质数");
}
}
}
}
字符串反序都有哪些算法?
最新推荐文章于 2022-08-28 14:51:27 发布