forked from Wang-Jun-Chao/coding-interviews
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Test42.java
102 lines (88 loc) · 2.82 KB
/
Test42.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/**
* Author: 王俊超
* Date: 2015-06-14
* Time: 10:40
* Declaration: All Rights Reserved !!!
*/
public class Test42 {
/**
* 将data中start到end之间的数字反转
*
* @param data
* @param start
* @param end
*/
public static void reverse(char[] data, int start, int end) {
if (data == null || data.length < 1 || start < 0 || end > data.length || start > end) {
return;
}
while (start < end) {
char tmp = data[start];
data[start] = data[end];
data[end] = tmp;
start++;
end--;
}
}
/**
* 题目一:输入一个英文句子,翻转句子中单词的顺序,但单词内字啊的顺序不变。
* 为简单起见,标点符号和普通字母一样处理。
*
* @param data
* @return
*/
public static char[] reverseSentence(char[] data) {
if (data == null || data.length < 1) {
return data;
}
reverse(data, 0, data.length - 1);
int start = 0;
int end = 0;
while (start < data.length) {
if (data[start] == ' ') {
start++;
end++;
} else if (end == data.length || data[end] == ' ') {
reverse(data, start, end - 1);
end++;
start = end;
} else {
end++;
}
}
return data;
}
/**
* 题目二:字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。
* 请定义一个函数实现字符串左旋转操作的功能。
* @param data
* @param n
* @return
*/
public static char[] leftRotateString(char[] data, int n) {
if (data == null || n < 0 || n > data.length) {
return data;
}
reverse(data, 0, data.length - 1);
reverse(data, 0, data.length - n - 1);
reverse(data, data.length - n, data.length - 1);
return data;
}
public static void main(String[] args) {
test01();
test02();
}
private static void test01() {
System.out.println(new String(reverseSentence("I am a student.".toCharArray())));
System.out.println(new String(reverseSentence("Wonderful".toCharArray())));
System.out.println(new String(reverseSentence("".toCharArray())));
System.out.println(new String(reverseSentence(" ".toCharArray())));
}
private static void test02() {
System.out.println(new String(leftRotateString("abcdefg".toCharArray(), 2)));
System.out.println(new String(leftRotateString("abcdefg".toCharArray(), 1)));
System.out.println(new String(leftRotateString("abcdefg".toCharArray(), 6)));
System.out.println(new String(leftRotateString("abcdefg".toCharArray(), 7)));
System.out.println(new String(leftRotateString("abcdefg".toCharArray(), 0)));
}
}