151.翻转字符串里的单词
思路
去掉多余的空白字符,拆分字符串,逆序拼接。还有种写法就是去掉多余空白字符,全反转,按每个空白字符划分再反转一次。
代码
class Solution {
public String reverseWords(String s) {
int i=0;
String[] directory=new String[s.length()];
int count=0;
int left=0;
while(i<s.length()){
if(s.charAt(i)==' '){
String temp=s.substring(left,i);
if(left!=i){
directory[count]=temp;
left=i+1;
count++;
}else{
while(i+1<s.length()&&s.charAt(i+1)==' ') i++;
left=i+1;
}
}
i++;
}
if(left<s.length()&&i==s.length()){
String temp=s.substring(left,i);
directory[count]=temp;
left=i+1;
count++;
}
String result="";
for(int j=count-1;j>=0;j--){
result+=directory[j];
if(j!=0){
result+=" ";
}
}
return result;
}
}
右旋字符串(acm模式)
思路
跟链表的删除倒数第K个元素一个思想。先让fast指针走k步,slow和fast再一起走。记得输入的时候吞掉一个回车符。
代码
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner in=new Scanner(System.in);
int k=in.nextInt();
in.nextLine();
String s=in.nextLine();
String result=change(s,k);
System.out.println(result);
}
public static String change(String s,int k){
String result="";
int slow=0;
int fast=0;
while(fast<k){
fast++;
}
while(fast<s.length()){
fast++;
slow++;
}
while(slow<s.length()){
result+=s.charAt(slow);
slow++;
}
if(k<s.length()){
result+=s.substring(0,s.length()-k);
}
return result;
}
}
实现 strStr()
思路
kmp
代码
class Solution {
public int strStr(String haystack, String needle) {
int[] next=new int[needle.length()];
int j=0;
next[0]=0;
for(int i=1;i<needle.length();i++){
while(j>0&&needle.charAt(i)!=needle.charAt(j)){
j=next[j-1];
}
if(needle.charAt(i)==needle.charAt(j)){
j++;
next[i]=j;
}
}
int k=0;
for(int i=0;i<haystack.length();i++){
while(k>0&&haystack.charAt(i)!=needle.charAt(k)){
k=next[k-1];
}
if(haystack.charAt(i)==needle.charAt(k)){
k++;
}
if(k==needle.length()){
return i-k+1;
}
}
return -1;
}
}
//a a b a a a b a a a c
//a a b a a a c
//0 1 0 1 2 2 0