字符串 按单词逆序

/**
 * London bridge is falling down --> down falling is bridge London
 * @author wdede
 *
 */

public class London {
	public static void main(String[] args) {
        //运行完rev():nwod gnillaf si egdirb nodnoL
		char[] s = rev("London bridge is falling down");
        //运行完subRev():down falling is bridge London
		subRev(s);
	}

	public static char[] rev(String str) { // 将整个字符串按字母倒置
		char temp;
		int len;
		len = str.length();
		char[] chr = str.toCharArray();
		for (int i = 0, j = len - 1; i < j; i++, j--) {
			temp = chr[j];
			chr[j] = chr[i];
			chr[i] = temp;
		}
		return chr;
	}

	public static void subRev(char[] chars) { //将每个单词正序(交换char数组中的位置即可)
		char temp;
		int len = chars.length;
		int i = 0, p = 0, q = 0;
		char ch;
		while (i < len) {
			while (chars[i++] != ' ') {
				q++;
				if (i == len) {
					break;
				}
			}

			for (int m = p, n = q - 1; m < n; m++, n--) {
				temp = chars[n];
				chars[n] = chars[m];
				chars[m] = temp;
			}
			q += 1;
			p = q;
		}
		System.out.println(chars);
	}

}

 

上一篇:算法与数据结构01


下一篇:Leetcode.443——压缩字符串