zoukankan      html  css  js  c++  java
  • lintcode:Length of Last Word 最后一个单词的长度

    题目:

    给定一个字符串, 包含大小写字母、空格' ',请返回其最后一个单词的长度。

    如果不存在最后一个单词,请返回 0 。

    样例

    给定 s = "Hello World",返回 5

    注意

    一个单词的界定是,由字母组成,但不包含任何的空格。

    解题:

    利用正则确认是字母,向前走,当遇到不是字母的时候跳出程序,为了合适的跳出定义一个布尔值,是字母的时候是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;
        }
    }
    View Code

    总耗时: 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
    View Code

    总耗时: 483 ms

  • 相关阅读:
    字符串,列表和元组-3
    数据和表达式-2
    python3.6.2(32位)的安装-1
    HTTP协议
    bug无法重现
    当开发说不是BUG时怎么办
    Python流程分类初试
    私有,封装
    Python继承
    编译型语言和解释型语言
  • 原文地址:https://www.cnblogs.com/theskulls/p/4886428.html
Copyright © 2011-2022 走看看