题目:
给定一个字符串, 包含大小写字母、空格' '
,请返回其最后一个单词的长度。
如果不存在最后一个单词,请返回 0
。
样例
给定 s = "Hello World"
,返回 5
。
注意 View Code View Code
一个单词的界定是,由字母组成,但不包含任何的空格。
解题:
利用正则确认是字母,向前走,当遇到不是字母的时候跳出程序,为了合适的跳出定义一个布尔值,是字母的时候是true,当不是字母同时布尔值是true时候跳出
Java程序:
public class Solution { /** * @param s A string * @return the length of last word */ public int lengthOfLastWord(String s) { // Write your code here int lenword = 0; boolean left = false; String match = "\\w"; for(int i= s.length()-1;i>=0;i--){ String str = s.substring(i,i+1); if(left==true &&str.matches(match)==false){ break; } if(str.matches(match)){ lenword+=1; left = true; } } return lenword; }}
总耗时: 11524 ms
Python程序:
class Solution: # @param {string} s A string # @return {int} the length of last word def lengthOfLastWord(self, s): # Write your code here lenword = 0 isAlpha = False for i in range(len(s)-1,-1,-1): tmp = s[i] if isAlpha==True and tmp.isalpha()==False: break if tmp.isalpha(): isAlpha = True lenword +=1 return lenword
总耗时: 483 ms