反转单词顺序以及左旋转字符串:输入一个英文句子,翻转句子中的单词顺序,单词内部的字母顺序是不变的 – I am a student. -> student. am I
第一步,翻转句子中的所有字符串,第二步翻转单词顺序
public class _Q42<T> {
public char[] ReverseSentence(String str){
if(str == null) return null;
if(str.length() == 0) return str.toCharArray();
char chars[] = str.toCharArray();
reverse(chars, 0, str.length() - 1);
int start = 0;
for(int i=0; i<str.length(); i++){
if(chars[i] == ' '){
reverse(chars, start, i - 1);
start = i + 1;
}
}
reverse(chars, start, str.length() - 1);
return chars;
}
private void reverse(char chars[], int begin, int end){
if(chars == null) return;
if(begin == end) return;
char c;
while(begin < end){
c = chars[begin];
chars[begin] = chars[end];
chars[end] = c;
begin++;
end--;
}
}
public char[] LeftRotateString(String str, int n){
if(str == null) return null;
char chars[] = str.toCharArray();
// 先分段旋转
reverse(chars, 0 , n - 1);
reverse(chars, n, str.length() - 1);
// 最后整体旋转
reverse(chars, 0, str.length() - 1);
return chars;
}
}
测试代码:
public class _Q42Test extends TestCase {
_Q42<?> reverse = new _Q42();
public void test(){
String str1 = "I am a student.";
System.out.println(reverse.ReverseSentence(str1)); // 需要对返回结果进行非空判断
String str2 = "abcdefg";
int n = 2;
System.out.println(reverse.LeftRotateString(str2, n)); //
}
}