1.给出s=“the sky is blue”,返回“blue is sky the”
public class Soultion{
public String reverseWords(String s){
if(s == null || s.length()==0){
return "";
}
String[] array = s.split(" ");
StringBuilder sb = new StringBuilder();
for(int i = array.length - 1; i >= 0; --i){
if(!array[i].equals("")){
sb.append(array[i].append(" "));
}
}
return sb.length() == 0 ? "":sb.substring(0,sb.length()-1);
}
}
2.给定一个字符串和一个偏移量,根据偏移量旋转字符串(从左向右旋转)
对于字符串“abcdefg”,
offset=0=>'abcdefg'
offset=1=>'gabcdef'
offset=2=>'fgabcde'
offset=3=>'efgabcd'
public class Solution{
public void rotateString(char[] str, int offset){
if(str == null || str.length == 0)
return;
// offset可以大于字符串长度
offset = offset % str.length;
reverse(str,0,str.length-offset-1);
reverse(str, str.length-offset,str.length-1);
reverse(str,0,str.length-1)
}
// 三段反转
private void reverse(char[] str, int start, int end){
for(int i = start, j = end; i < j; i++, j--){
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}