字符串反序都有哪些算法?

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 +"是质数");
			}
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值