LeetCode - The World's Leading Online Programming Learning Platform
1 <= s.length <= 104
s
consists of only English letters and spaces ' '
.s
.문자열의 길이가 짧음 + 고려사항이 거의 없음 → 문제의 조건대로 구현
문자열의 끝에서부터 갯수 카운트
trimEnd()
로 끝에 붙어있는 공백 제거
class Solution {
fun lengthOfLastWord(s: String): Int {
var cnt = 0
for (c in s.trimEnd().reversed()) {
if (c != ' ') {
cnt++
} else return cnt
}
return cnt
}
}
시간 복잡도: 문자열 순회 = n