// 题目1:输入一个英文句子,翻转其中的每一个单词
public class Main {
public static void main(String[] args) throws Exception {
System.out.println(reverseWord("welcome to tencnet"));
}
public static String reverseWord(String input) {
if (input == null) {
return null;
}
char[] str = input.toCharArray(); // 统一翻转
reverse(str, 0, input.length() - 1);
int low = 0;
int high = 0;
for (int i = 0; i < input.length(); i++) {
if (i == input.length() - 1) { // 最后一个单词翻转不同
reverse(str, low, high);
break;
}
if (str[i] != ' ') { // 翻转每个单词
high++;
continue;
}
reverse(str, low, high - 1);
low = high + 1;
high = low;
}
return new String(str);
}
public static void reverse(char[] str, int low, int high) { // 对str从low到high翻转
while (low < high) {
char temp = str[low];
str[low] = str[high];
str[high] = temp;
low++;
high--;
}
}
}
//题目2:输入一个字符串和一个整型位置,在此位置上对字符串进行左旋转
public class Main {
public static void main(String[] args) throws Exception {
System.out.println(reverseWord("abc",2));
}
public static String reverseWord(String input, int index) {
if(input == null || index>input.length()){
return null;
}
char[] str = input.toCharArray();
reverse(str,0,index-1); //翻转index前的字符串
reverse(str,index,input.length()-1); //翻转index后的字符串
reverse(str,0,input.length()-1); //翻转str
return new String(str);
}
public static void reverse(char[] str, int low , int high){ //对str从low到high翻转
while(low<high){
char temp = str[low];
str[low] = str[high];
str[high] = temp;
low++;
high--;
}
}
}
剑指offer 42. 翻转单词顺序VS左旋转字符串
最新推荐文章于 2022-08-19 10:22:11 发布