LeetCode

落爺英雄遲暮 提交于 2020-12-12 13:51:32

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(" "));
	}
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!