public class Test {
public static void main(String[] args) {
String str = " Huang Biao jorneyr inhibitory a b";
char[] chars = str.toCharArray();
trim(chars);
}
// 删除字符串前面的空格,删除字符串中间单词间的多个空格,只留一个。
// 不重新申请空间,复杂度O(N)
public static void trim(char[] chars) {
int finalIndex = 0;
int spaceCount = 0;
for (int i = 0; i < chars.length; ++i) {
if (chars[i] != ' ') {
chars[finalIndex] = chars[i];
++finalIndex;
spaceCount = 0;
} else if (chars[i] == ' ' && finalIndex == 0) {
} else if (chars[i] == ' ' && spaceCount == 0) {
chars[finalIndex] = chars[i];
++finalIndex;
++spaceCount;
} else if (chars[i] == ' ' && spaceCount > 0) {
++spaceCount;
}
}
System.out.println(chars);
for (int i = finalIndex; i < chars.length; ++i) {
chars[i] = ' ';
}
System.out.println(chars);
}
}