字符串reverse

阅读更多

package com.myway.study;

/**
 * 编程珠玑的题目:
 * 举例:比如abcdef 左移三位,则变成defabc
 * 

* 条件限制:空间限制:可用内存为几十字节 *

* 时间限制:花费时间与n成比例 * User: zhangyong * Date: 14-5-27 * Time: 下午8:24 * To change this template use File | Settings | File Templates. */ public class Reverse { public static char[] reverse(char[] arr, int start, int end) { int n = arr.length; // abc 奇数 // abcd 偶数 int mid = (start + end) / 2; for (int i = start, j = end; i <= mid; i++, j--) { char temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } return arr; } public static char[] leftRotateString(char[] arr, int k) { //字符串abcdefgh -> defghabc // 需要三步: // reverse(0,i-1); //cba defgh // reverse(i,n-1); //cba hgfed // reverse(0,n-1); //defghabc int n = arr.length; reverse(arr, 0, k - 1); reverse(arr, k, n - 1); reverse(arr, 0, n - 1); return arr; } public static void main(String[] args) { char[] arr = "abcdefg".toCharArray(); leftRotateString(arr, 3); System.out.println(arr); } }

你可能感兴趣的:(编程,java,算法珠玑)