hahn

[LeetCode - C] 58. Length of Last Word 본문

코딩테스트 연습/LeetCode(C - Easy)

[LeetCode - C] 58. Length of Last Word

hahn 2022. 4. 12. 21:19
728x90
반응형
 

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

Given a string s consisting of some words separated by some number of 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: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.

Example 2:

Input: s = "   fly me   to   the moon  "
Output: 4
Explanation: The last word is "moon" with length 4.

Example 3:

Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.

 

Constraints:

  • 1 <= s.length <= 104
  • s consists of only English letters and spaces ' '.
  • There will be at least one word in s.

Solution 1

 

string 끝까지 idx 이동시키고

 

뒤에 공백이 있다면 idx--

 

이후 공백을 만나거나 idx가 -1이 될 때 까지

 

idx--함과 동시에 len++

 

이후 len return

 

int lengthOfLastWord(char *s)
{
    int len;
    int idx;
    
    idx = 0;
    len = 0;
    while (s[idx])
        idx++;
    idx--;
    while (s[idx] == ' ')
        idx--;
    while (idx != -1 && s[idx] != ' ')
    {
        idx--;
        len++;
    }
    return (len);
}
728x90
반응형