`
leonzhx
  • 浏览: 788639 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Quesion 1b Character-wise shift for String

 
阅读更多

After reading the solution and thoughts of July , I found that the last solution is quite succinct and beautiful. The major thought is that to make AB to BA (while A and B are sub-string of the original string), we can do the following : (A^B^)^  , while A^ means the reverse of A in character. Java implementation is provided below :

public class StringShift {

	public static void main(String[] args) {
		//m & n has no common factors
		assert "DEFGABC".equals(shift("ABCDEFG", 3, true));
		assert "EFGABCD".equals(shift("ABCDEFG", 3, false));
		
		//n is multiple of m
		assert "EFGHABCD".equals(shift("ABCDEFGH", 4, true));
		assert "EFGHABCD".equals(shift("ABCDEFGH", 4, false));
		
		//n and m shares a common factor
	    assert "GHIABCDEF".equals(shift("ABCDEFGHI", 6, true));
		assert "DEFGHIABC".equals(shift("ABCDEFGHI", 6, false));
		
	}
   
	/**
	 *   AB --->  (A^B^)^ ---> BA
	 *   while A^ is the reverse order of A
	 * 
	 */
	private static Object shift(String origin, int m, boolean left) {
		
		//input check
		if ( origin == null) return null;
		
		int len = origin.length();
		
		if (m == 0) return origin;
		
		m = left ? m : -m;
		
		
		// calulate the size of A
		int l = ( m + len ) % len;
		
		char[] arr = new char[len];
		
		origin.getChars(0, len, arr, 0);
		
		reverse(arr , 0 , l);
		reverse(arr , l , len);
		reverse(arr , 0 , len);
		
		return new String(arr);
	}
	
	private static void reverse(char[] arr , int start , int end) {
		
		char temp;
		for ( int s = start , e = end - 1 ; s < e ; s ++, e -- ) {
			temp = arr[s];
			arr[s] = arr[e];
			arr[e] = temp;
		}
}

 

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics