[LeetCode] 12.Length of Last Word

2021. 1. 14. 16:52

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

 

Length of Last Word - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

1. Problem

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 <= 104
  • s consists of only English letters and spaces ' '.

 

2. Code

package leetCode;

public class LengthOfLastWord {

	public static void main(String[] args) {
		String s = "Hello World";
		System.out.println(lengthOfLastWord(s));
	}
    public static int lengthOfLastWord(String s) {
        String[] sArr = s.split(" ");
    	if(sArr.length == 0) {
    		return 0;
    	}
        return sArr[sArr.length-1].length();
    }
}

 

3. Report

 

문자열 자르기

String은 char을 여러개 합친 것과 같다.

ex) String s = "Hello World!";    == 'H' + 'e' + . . . + 'l' + 'd' + '!' ;

s.charAt(0) = H

s.charAt(1) = e

s.charAt(2) = l

.

.

charAt을 사용하면 문자열의 해당 index 값에 있는 char형이 나온다.

 

1) Substring

String.substring(start) // start 위치부터 끝까지 문자열 자르기

String.substring(start,end) // start부터 end까지 문자열 자르기

 

 

2) Split

-특정문자열 기준으로 나눠서 배열에 저장해준다

String[] sArr = string.split(" "); // 띄어쓰기 기준으로 배열에 저장해줌

String[] sArr = string.split("/"); // / 기준으로 배열에 저장해줌

 

 

 SubString  S

 

 

 

 SdddddddddddddddddubString 

BELATED ARTICLES

more