华为OJ平台练习题

来源:互联网 发布:下载模组的软件 编辑:程序博客网 时间:2024/05/16 17:38

字符串最后一个单词的长度(2016-04-10)


题目描述

描述 计算字符串最后一个单词的长度,单词以空格隔开。 知识点 字符串,循环 运行时间限制 0M 内存限制 0 输入 一行字符串,长度小于128。 输出 整数N,最后一个单词的长度。 样例输入 hello world 样例输出 5

解题思路

利用空字符串将字符串分隔成数组,然后获取数组最后一个元素,也就是字符串最后一个单词,然后获取字符串的长度即可。

代码

Java:

import java.util.*;    public class Main{        public static int lengthOfLast(String str) {            String[] s =str.split(" ");            return s[s.length-1].length();        }        public static void main(String[] args) {            Scanner scan = new Scanner(System.in);            while(scan.hasNext()){                String str = scan.nextLine();                System.out.println(lengthOfLast(str));            }        }    }

Python:

class Soultion:    # @param {string} A string    # @return {int} the length of last word    def lengthOfLastWord(s):        if(len(s) >= 128):            return -1        else:            # Write your code here            list = s.split()            lastword = list[-1]            return len(lastword)    if __name__ == '__main__':        string = raw_input('')        length = lengthOfLastWord(string)        print(length)

欢迎相互交流!!!O(∩_∩)O~

0 0
原创粉丝点击