}String[] arr = s.split(" ");returnarr[arr.length-1].length(); } 04 第三种解法 将原字符串首尾的空格去掉,然后找到最后一次出现空格的位置,两者相减再减1即为最后单词的长度。 public intlengthOfLastWord3(String s) { return s.trim().length()-s.trim().lastIndexOf(" ")-1; } 05 小结...
leetcode 58. Length of Last Word 找最后一个word的长度。 从后往前计算,找到第一个不是空的位置,然后从这个位置再继续找第一个为空的位置 classSolution {public:intlengthOfLastWord(strings) {intright = s.size() -1;while(right >=0){if(s[right] =='') right--;elsebreak; }intleft =right;...
For example, Given s = “Hello World”, return 5. 解题思路:遇到非’ ‘字符,用一个符号表示word開始,遇到’ ‘表示word结束,注意边界情况处理 优化:能够从字符串末尾開始处理 class Solution { public: int lengthOfLastWord(string s) { int strLen = s.length(); if(strLen == 0) return 0; int...
方法2:使用字符串输入输出流直接可以自动过滤空格 class Solution { public: int lengthOfLastWord(string s) { stringstream ss(s); string word; while(ss>>word); return word.size(); } }; 1. 2. 3. 4. 5. 6. 7. 8. 9.
Can you solve this real interview question? Length of Last Word - Given a string s consisting of words and spaces, return the length of the last word in the string. A word is a maximal substring consisting of non-space characters only. Example 1:
[LeetCode]58.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. If the last word does not exist, return 0. Note: A ... ...
public class Solution { public static int lengthOfLastWord(String s) { s = s.trim(); // 去掉字符串首尾的空格 int i = 0; for (i = s.length() - 1; i >= 0; --i) { if (s.substring(i, i + 1).equals(" ")) {
LeetCode 58: Length of Last Word 題目描述 題目說明:給一個字串,裡面可能包含英文字母(alphabets) 與空格(space)。回傳最後一個單字(word)的長度。 例如: "Hello World ", 應回傳 5, 因為 World 的長度為 5。 TDD 開始 Step 1, 新增測試用例。長度為2, 不含空格的 word。 s 為"bc" ...
Source File: solution.cpp From LeetCode-NOTES with MIT License 5 votes int lengthOfLastWord(const char *s) { int result = 0; bool flag = false; while(*s != '\0') { if(*s == ' ') flag = true; else if(flag == true) { flag = false; result = 1; } else ...
Leetcode 58. 最后一个单词的长度 Length of Last Word 标签: Leetcode 题目地址:https://leetcode-cn.com/problems/length-of-last-word/ 题目描述 给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。 如果不存在最后一个单词,请返回 0 。 说明:一个单...[...