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
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();
}
};
가볍게 터치!
'Coding_Practice' 카테고리의 다른 글
Binary Tree Inorder Traversal[E,Stack,Tree,Depth-First Search,Binary Tree] (0) | 2024.07.31 |
---|---|
C++ Container, Custom Map Practice (0) | 2024.07.29 |
Merge Sorted Array[E,Array,Two Pointers,Sorting] (0) | 2024.07.27 |
Search Insert Position[E,Array,Binary Search] (0) | 2024.07.27 |
Convert 1D Array Into 2D Array[E,Array,Matrix,Simulation] (0) | 2024.07.26 |