티스토리 뷰
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.
첫 번째
일단 풀었는데, runtime이 2ms라서 다시 풀어야한다. runtime 0ms되기까지!
class Solution {
public int lengthOfLastWord(String s) {
String[] words = s.trim().split("\\s+");
int count = words.length;
String res = words[count-1];
return res.length();
}
}
두 번째
결국 다른 분꺼 참고해서 풀었다. 마지막 단어 인덱스만 구하면 되었으므로 마지막 단어 맨 뒤 인덱스랑 맨 앞 인덱스를 찾아서 뒤 인덱스 - 앞 인덱스를 빼주면된다.
class Solution {
public int lengthOfLastWord(String s) {
int i = s.length() - 1;
while(i>=0 && s.charAt(i) == ' ') --i;
final int lastIndex = i; // 마지막 단어 맨 뒤
while(i>=0 && s.charAt(i) != ' ') --i; // 마지막 단어 맨 앞
return lastIndex - i;
}
}
반응형
LIST
'백준&LeetCode' 카테고리의 다른 글
[프로그래머스] 둘만의 암호 (0) | 2025.03.02 |
---|---|
[프로그래머스] 핸드폰 번호 가리기 java (0) | 2025.02.27 |
[LeetCode] 35. Search Insert Position (Day3) (0) | 2024.01.10 |
[LeetCode] 13. Roman to Integer (Day2) (0) | 2024.01.09 |
[LeetCode] 872. Leaf-Similar Trees (Day2) (0) | 2024.01.09 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- yolov8
- 파이썬
- 에러발생
- 문제풀이
- SPRING오류해결
- 10828번
- 터틀그래픽
- database연결
- 터틀그래픽 명령어
- baekjoon
- tweepy
- 사람수세기
- randrange
- Kkma
- JAVA오류해결
- UnsupportedClassVersionError
- 터틀그래픽예제
- konlpy
- randint
- YOLO
- 다인승
- streamlistener
- 오븐시계
- Turtle Graphic
- 다인승탑승
- python공부
- 백준
- gradleload오류
- 사람검출
- springboot
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 |
글 보관함
반응형