코딩테스트/Leetcode

Leetcode [Java] :: 58. Length of Last Word

블로그 주인장 2023. 9. 2.

🎁 문제 링크

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

 

Length of Last Word - LeetCode

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: Input:

leetcode.com

🎁 문제 설명

  • 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.
  • s단어와 공백으로 구성된 문자열이 주어 지면 문자열의 마지막 단어 길이를 반환합니다. 말 한마디 가 최대치다 하위 문자열 공백이 아닌 문자로만 구성됩니다.

🎁 입출력 예시

🎁 코드

class Solution {
    public int lengthOfLastWord(String s) {
        String[] s1 = s.split(" ");

        String answer = s1[s1.length - 1];
        System.out.print(answer);
        
        return answer.length();
    }
}

🎁 코드 설명

1) s의 마지막 문자열의 갯수를 파악하는 문제이다.

2) 문자열 안에 있는 공백을 없앤 배열을 만들고 해당 배열의 마지막 문자의 갯수를 리턴한다.

반응형

댓글