Java 服务端架构
🎨 视觉封面LeetCode Length of Last Word
Problem
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 word is defined as a character sequence consists of non-space characters only.
Example:
Input: "Hello World" Output: 5
简单题,计算字符串最后一个非空字符串的长度。
Java 实现
package com.coderli.leetcode.algorithms.easy;
/**
* Given a string s consists of upper/lower-case alphabets and empty space characters ' ',
* return the length of last word in the string.
* <p>
* If the last word does not exist, return 0.
* <p>
* Note: A word is defined as a character sequence consists of non-space characters only.
* <p>
* Example:
* <p>
* Input: "Hello World"
* Output: 5
*
* @author li.hzh 2017-11-07 12:22
*/
public class LengthOfLastWord {
public static void main(String[] args) {
LengthOfLastWord lengthOfLastWord = new LengthOfLastWord();
System.out.println(lengthOfLastWord.lengthOfLastWord("Hello World"));
System.out.println(lengthOfLastWord.lengthOfLastWord("a "));
System.out.println(lengthOfLastWord.lengthOfLastWord("b a "));
}
public int lengthOfLastWord(String s) {
if (s == null || s.length() == 0) {
return 0;
}
int lastLength = 0;
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) != ' ') {
lastLength++;
} else if (lastLength == 0){
continue;
} else {
break;
}
}
return lastLength;
}
}
分析
极简题,没什么可说的。只需要注意连续空格即可。例如:"b a " 返回 1。
所有代码开源上传至 GitHub:yummy-code 仓库 · GESP 专题站:GESP WIKI
欢迎加入:C++ GESP/CSP 考级答疑群(688906745) 与 Java/Python交流群(982860385),点击可直接加群。
猜你想读 · 相关文章推荐
LeetCode Palindrome Number
Problem Determine whether an integer is a palindrome. Do this without extra space. 即返回一个数是否是回数。例如:1,1221,12321是回数,负数不是回数。题目特别提醒,不要使用额外的...
LeetCode Reverse Integer
Problem Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 Note: The input is assumed to be a...
LeetCode Roman to Integer
Problem Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. 即将罗马数字1-3999转换成对应的整...
OneCoder
一个中年人的自留地,记录学习 C++、GESP/NOI、Java、Python 与算法架构的心得体会。本站唯一网址:coderli.com

