问题:
给一个字符串,比如 “I love china”, 把字符反转后变成 “china love I”
思路:
先把字符串从第一个字符与最后一个字符对换,第二个字符和倒数第二个字符对换,这样,我们就把每一个单词位置互换了。但是我们要求单词里面字符的顺序是不能变的,所以,我们要把每一个单词里面的字符从头到尾对换一下。这样就可以得到我们想要的字符串了。
实现:
因为这里两次都会用到字符反转,所以我们就单独写一个swap的方法出来。我们对每个单词进行发转的时候,需要记录每个单词的起始点和结束点,对于第一个单词,起始点是0,最后一个单词,结束点是string.length() - 1。而中间的单词,开始点和结束点是空格的位置。
代码如下:
public class ReverseString {
//reverse the string
public void swap(StringBuilder sb, int begin, int end) {
while (begin < end) {
char temp = sb.charAt(begin);
sb.setCharAt(begin, sb.charAt(end));
sb.setCharAt(end, temp);
begin++;
end--;
}
}
public String reverse(StringBuilder sb) {
if (sb == null || sb.length() == 0 ) {
return null;
}
//first, reverse the whole string without considering the order of the character in each word
int end = sb.length() - 1;
swap(sb, 0, end);
//array position records the beginning index and ending index of each word
int[] position = new int[sb.length()];
//set the first position to -1
position[0] = -1;
int j = 1;
for (int i = 0; i < end; i++) {
if (sb.charAt(i) == ' ') {
position[j] = i;
j++;
}
}
position[j] = sb.length();
//reverse the order of the character in each word
for (int i = 0; i < j ; i++) {
swap(sb, position[i]+1, position[i+1]-1);
}
return sb.toString();
}
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("I LOVE CHINA!");
ReverseString rs = new ReverseString();
System.out.println(rs.reverse(sb));
}
}
转载请注明出处:http://blog.youkuaiyun.com/beiyeqingteng