1. 程式人生 > 其它 >LeetCode - Easy - 58. Length of Last Word

LeetCode - Easy - 58. Length of Last Word

技術標籤:LeetCode演算法與資料結構字串

Topic

String

Description

https://leetcode.com/problems/length-of-last-word/

Given a string s consists of some words separated by spaces, return the length of the last word in the string. If the last word does not exist, return 0.

A word is a maximal substring consisting of non-space characters only.

Example 1:

Input: s = "Hello World"
Output: 5

Example 2:

Input: s = " "
Output: 0

Constraints:

  • 1 <= s.length <= 10⁴
  • s consists of only English letters and spaces ’ '.

Analysis

Submission

public class LengthOfLastWord {
    public int lengthOfLastWord1(String s) {
        String[
] array = s.split(" "); return array.length > 0 ? array[array.length - 1].length() : 0; } public int lengthOfLastWord2(String s) { String temp = s.trim(); return temp.length() - temp.lastIndexOf(" ") - 1; } }

Test

import static org.junit.Assert.
*; import org.junit.Test; public class LengthOfLastWordTest { @Test public void test() { LengthOfLastWord obj = new LengthOfLastWord(); assertEquals(5, obj.lengthOfLastWord1("Hello World")); assertEquals(0, obj.lengthOfLastWord1(" ")); assertEquals(5, obj.lengthOfLastWord2("Hello World")); assertEquals(0, obj.lengthOfLastWord2(" ")); } }