看到同事出去的面试题,将“hello world” 转换成 “ world hello"还要考虑空间复杂度
然后就随便写写,主要是c思路,用c语言估计可以更简洁,也不知道是不是面试官想要的答案
String s = "hello world 123 321";
Field f = s.getClass().getDeclaredField("value");
f.setAccessible(true);
char[] chrs = (char[]) f.get(s);
char temp;
for (int i = 0; i < chrs.length / 2; i++) {
temp = chrs[i];
chrs[i] = chrs[chrs.length - i - 1];
chrs[chrs.length - i - 1] = temp;
}
System.out.println(s);
int lastIndex = 0;
for (int i = 0; i < chrs.length; i++) {
if (chrs[i] == ' ' || i == chrs.length - 1) {
if (i == chrs.length - 1)
i = i + 1;
for (int j = lastIndex; j < lastIndex + (i - lastIndex) / 2; j++) {
temp = chrs[j];
chrs[j] = chrs[i - j - 1 + lastIndex];
chrs[i - j - 1 + lastIndex] = temp;
}
lastIndex = i + 1;
}
}
System.out.println(s);
网友评论