java实现字符串反转 [#2]

问题:

给一个字符串,比如 “I love china”, 把字符反转后变成 “china love I”

思路:

先把字符串从第一个字符与最后一个字符对换,第二个字符和倒数第二个字符对换,这样,我们就把每一个单词位置互换了。但是我们要求单词里面字符的顺序是不能变的,所以,我们要把每一个单词里面的字符从头到尾对换一下。这样就可以得到我们想要的字符串了。

实现:

因为这里两次都会用到字符反转,所以我们就单独写一个swap的方法出来。我们对每个单词进行发转的时候,需要记录每个单词的起始点和结束点,对于第一个单词,起始点是0,最后一个单词,结束点是string.length() - 1。而中间的单词,开始点和结束点是空格的位置。

代码如下:

public class ReverseString {
	
	//reverse the string 
	public void swap(StringBuilder sb, int begin, int end) {
		while (begin < end) {
			char temp = sb.charAt(begin);
			sb.setCharAt(begin, sb.charAt(end));
			sb.setCharAt(end, temp);
			begin++;
			end--;
		}
	}
	
	public String reverse(StringBuilder sb) {
		
		if (sb == null || sb.length() == 0 ) {
			return null;
		}
		
		//first, reverse the whole string without considering the order of the character in each word
		int end = sb.length() - 1; 
		swap(sb, 0, end);
		
		//array position records the beginning index and ending index of each word
		int[] position = new int[sb.length()];
		//set the first position to -1
		position[0] = -1;
		int j = 1;
		for (int i = 0; i < end; i++) {
			if (sb.charAt(i) == ' ') {
				position[j] = i;
				j++;
			}
		}
		position[j] = sb.length();
		
		//reverse the order of the character in each word
		for (int i = 0; i < j ; i++) {
			swap(sb, position[i]+1, position[i+1]-1);
		}
		
		return sb.toString();
		
	}

	public static void main(String[] args) {
		StringBuilder sb = new StringBuilder("I LOVE CHINA!");
		ReverseString rs = new ReverseString();
		
		System.out.println(rs.reverse(sb));
		
	}
}

转载请注明出处:http://blog.youkuaiyun.com/beiyeqingteng

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值