Eat Study Love

먹고 공부하고 사랑하라

Coding_Practice

Length of Last Word[E,String]

eatplaylove 2024. 7. 27. 23:16

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

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

1. Python

 

가볍게 원샷 원킬

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        s=s.strip()
        ans = 0
        for i in range(len(s)-1,-1,-1):
            if s[i] != " ":
                ans+=1
            else:
                break
        return ans

 

 

GPT 풀이 below

1줄이다 ;;

def lengthOfLastWord(s: str) -> int:
    return len(s.strip().split()[-1])

 

 

2. C

폭풍 if문으로 풀이완료

int lengthOfLastWord(char* s) {
    int n = strlen(s);
    int ans = 0;
    bool first = true;
    for(int i=n-1;i>=0;i--){
        if(s[i]==' '&& first)
            continue;
        if(s[i]==' '&& !first)
            break;
        if(s[i]!=' '){
            ans++;
            first = false;
        }
    }
    return ans;
}

 

 

GPT풀이 below

int lengthOfLastWord(char * s){
    int length = 0;
    int i = strlen(s) - 1;

    // Trim the trailing spaces
    while (i >= 0 && s[i] == ' ') {
        i--;
    }

    // Count the length of the last word
    while (i >= 0 && s[i] != ' ') {
        length++;
        i--;
    }

    return length;
}

 

뭐.. 맥락은 비슷하다. while문 두 번 써서 맨 뒤에 빈칸 다 없애버리고, counting 하는 것

 

 

3. C++ (string stream)

class Solution {
public:
    int lengthOfLastWord(string s) {
        std::stringstream ss(s);
        std::string word;
        std::string lastword;

        while(ss >> word){
            lastword = word;
        }
        return lastword.length();
    }
};

 

가볍게 터치!