728x90
https://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
stringstream과 getline으로 문자열을 구분자로 구분해서 하려고 했는데, ex2에서 구분자 " "로는 안되길래 그냥 뒤에서부터 단어의 길이를 세줬다.
int lengthOfLastWord(string s) {
int answer = 0;
for(int i=s.size()-1; i>=0; i--){
if(answer == 0){
if(s[i] == ' ') continue;
else answer++;
}else{
if(s[i] == ' ') break;
else answer++;
}
}
return answer;
}
728x90
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode/easy] Valid Palindrome (0) | 2022.08.12 |
---|---|
[LeetCode/easy] Add Binary (0) | 2022.08.12 |
[LeetCode/easy] strStr() (0) | 2022.08.12 |
[LeetCode/easy] Valid Parentheses (0) | 2022.08.12 |
[LeetCode/easy] Longest Common Prefix (0) | 2022.04.18 |