标签:logs turn string bsp ret word index code for
求最后一个单词的长度
Java 1:
1 class Solution { 2 public int lengthOfLastWord(String s) { 3 int len=0; 4 int flag=0; 5 for(int i=s.length()-1;i>=0;--i){ 6 if(s.charAt(i)!=‘ ‘){ 7 if(flag == 0) 8 flag = 1; 9 len++; 10 } 11 if((i==0||s.charAt(i) == ‘ ‘)&&flag==1) 12 return len; 13 } 14 return len; 15 } 16 }
java 2:
class Solution { public int lengthOfLastWord(String s) { return s.trim().length() - s.trim().lastIndexOf(" ") -1; } }
Java 3:
class Solution { public int lengthOfLastWord(String s) { String[] str = s.split(" "); return str[str.length-1].length(); } }
标签:logs turn string bsp ret word index code for
原文地址:http://www.cnblogs.com/fcyworld/p/7646812.html