易宝机试题 翻转字符串

翻转字符串:时间限制:2秒、内存限制:262144K

给一个字符类型的数组chas和一个整数size,请把大小为size的左半区整体右移到右半区,右半区整体移动到左边。输入描述:

(1<=size<=chars.length<=10000)

输入两行,第一行一个整数,代表size,第二行一个字符串,代表chas 输出描述:输出一行字符串,代表翻转后的字符串。备注:时间复杂度 O(n),额外空间复杂度O(1)

示例1:

输入

3

abcdefg

输出

defgabc

题目是我应聘易宝时的机试题目,虽然题目有要求时间复杂度和空间复杂度,若非人工阅读代码,其实难以检查代码的时间复杂度和空间复杂度。我当时用的是一个时间复杂度O(n)、空间复杂度O(n)方法,牛客网测试依然都通过。下面分享我的一个时间复杂度O(n)、空间复杂度O(1)的实现方法

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		String content = null;
		int size = 0;
		char[] chars;
		while (scanner.hasNext()) {
			size = scanner.nextInt();
			content = scanner.next();
			break;
		}
		if (scanner != null) {
			scanner.close();
		}
		if (content != null && !content.isEmpty()) {
			chars = content.toCharArray();
			int len = (chars == null ? 0 : chars.length);
			int i1 = 0;
			int i2 = size - 1;
			int j1 = size;
			int j2 = len - 1;
			char c;
			int leftSize = size;
			int rightSize = len - size;

			if (size < len) {
				while (true) {
					if (leftSize == rightSize) {
						for (int i = i1, j = j1; i <= i2; i++, j++) {
							c = chars[i];
							chars[i] = chars[j];
							chars[j] = c;
						}
						break;
					}
					if (leftSize < rightSize) {
						if (leftSize != 1) {
							for (int i = i2, j = j2; i >= i1; i--, j--) {
								c = chars[i];
								chars[i] = chars[j];
								chars[j] = c;
							}
							rightSize -= leftSize;
							j2 = j1 + rightSize - 1;
						} else {
							for (int j = i1; j < j2; j++) {
								c = chars[j];
								chars[j] = chars[j + 1];
								chars[j + 1] = c;
							}
							break;
						}
					}
					if (leftSize > rightSize) {
						if (rightSize != 1) {
							for (int i = i2, j = j2; j >= j1; i--, j--) {
								c = chars[i];
								chars[i] = chars[j];
								chars[j] = c;
							}
							leftSize -= rightSize;
							i2 = leftSize - 1;
							j1 = leftSize;
							j2 = j1 + rightSize - 1;
						} else {
							for (int j = j1; j > i1; j--) {
								c = chars[j];
								chars[j] = chars[j - 1];
								chars[j - 1] = c;
							}
							break;
						}
					}
				}
			}
			System.out.println(chars);
		}
	}
}

 

你可能感兴趣的:(算法)