标签:
Length of Last Word
问题:
Given a string s consists of upper/lower-case alphabets and empty space characters ‘ ‘
, return the length of last word in the string.
思路:
string的API操作
我的代码:
public class Solution { public int lengthOfLastWord(String s) { if(s == null) return 0; s = s.trim(); if(s.length() == 0) return 0; String[] words = s.split(" "); int len = words.length; return words[len-1].length(); } }
他人代码:
public class Solution { public int lengthOfLastWord(String s) { int length = 0; char[] chars = s.toCharArray(); for (int i = s.length() - 1; i >= 0; i--) { if (length == 0) { if (chars[i] == ‘ ‘) { continue; } else { length++; } } else { if (chars[i] == ‘ ‘) { break; } else { length++; } } } return length; } }
学习之处:
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4330777.html