剑指Offer(四十四):翻转单词顺序序列
import java.util.*; public class Solution { public String ReverseSentence(String str) { if(str.trim().equals("")){ return str; } String[] s=str.split(" "); StringBuffer sb=new StringBuffer(); for(int i=s.length-1;i>=0;i--){ sb.append(s[i]); if(i!=0){ sb.append(" "); } } return sb.toString(); } }
public class Solution { public String ReverseSentence(String str) { char[] chars=str.toCharArray(); reverse(chars,0,str.length()-1); int blank=-1; for(int i=0;i<str.length();i++){ if(chars[i]==' '){ int nextblank=i; reverse(chars,blank+1,nextblank-1); blank=nextblank; } } reverse(chars,blank+1,str.length()-1); return new String(chars); } public void reverse(char[] chars,int low,int high){ while(low<high){ char temp=chars[low]; chars[low]=chars[high]; chars[high]=temp; low++; high--; } } }
剑指Offer(四十九):把字符串转换成整数
public class Solution { public int StrToInt(String str) { if(str==null||str.trim().equals("")){ return 0; } int symbol=1; int start=0; char[] chars=str.trim().toCharArray(); if(chars[0]=='+'){ start=1; }else if(chars[0]=='-'){ symbol=-1; start=1; } int result=0; for(int i=start;i<chars.length;i++){ if(chars[i]>'9'||chars[i]<'0'){ return 0; } result=result*10+(int)(chars[i]-'0'); if((symbol==1&&result>Integer.MAX_VALUE)||(symbol==-1&&-result<Integer.MIN_VALUE)){ return 0; } } return symbol*result; } }
剑指Offer(五十二):正则表达式匹配