class Solution {
public String reverseWords(String s) {
//移除空格
StringBuilder sb = removeSpace(s);
//反转字符串
reverseString(sb, 0, sb.length() - 1);
//反转单词
reverseWord(sb);
return sb.toString();
}
private StringBuilder removeSpace(String s){
//如果第一个和最后一个是空格,先删掉
int start = 0;
int end = s.length() - 1;
while (s.charAt(start) == ' '){
start++;//charAt()方法用于返回指定索引处的字符
}
while (s.charAt(end) ==' '){
end--;
}
StringBuilder sb = new StringBuilder();
while(start <= end){
char c = s.charAt(start);
if (c!=' ' || sb.charAt(sb.length()-1) != ' '){
sb.append(c);
}
start++;
}
return sb;
}
public void reverseString(StringBuilder sb, int start, int end){
while (start < end){
char temp = sb.charAt(start);
sb.setCharAt(start, sb.charAt(end));
sb.setCharAt(end, temp);
start++;
end--;
}
}
private void reverseWord(StringBuilder sb){
int start = 0;
int end = 1;
int n = sb.length();
while (start < n){
while(end <n && sb.charAt(end) != ' '){
end++;
}
reverseString(sb, start, end - 1);
start = end + 1;
end = start + 1;
}
}
}
public class Main {
public static void main(String[] args) {
//获取反转数和字符串
Scanner in = new scanner(System.in);
int n = Integer.parseInt(in.nextLine())//parseint 把字符串转换成整数
String s = in.nextLine();
//字符串转换为字符数组方便处理
int len = s.length();
char[] ch = s.toCharArray();
//字符反转
reserveString(ch, 0 , len - n- 1);
reserveString(ch, len - n - 1, len - 1);
reserveString(ch, 0, len - 1);
return ch;
}
public static void reserveString(char[], int start , int end){
while(start < end){
char temp ^= ch[start];
ch[start] ^= ch[end];
ch[end] ^= temp;
start++;
end--;
}
}
}
//啊啊状态不好,kmp不太懂
class Solution {
public int strStr(String haystack, String needle) {
int haystackLen = haystack.length();
int needleLen = needle.length();
if (needleLen = 0 || haystackLen ==0){
return 0 ;
}
if(haystackLen < needleLen){
return 0;
}
//找到首字母相等
int i = 0;
int j = 0;
while(i < n - m - 1){
while(haystack.charAt(i) != needle.charAt(j)){
i++;
}
if(i = n){
return -1;
}
//遍历后续字符
i++;
j++
while(i < haystackLen && j < needleLen && haystack.charAt(i) == needle.charAt(j) ){
i++;
j++;
}
if (j == needleLen){
return i - j;
}else{
i -= j-1;
j=0;
}
}
return -1;
}
}