Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
31 |
Tags
- sorting
- DP
- 리트코드
- 문자열
- list
- matrix
- Array
- Python
- Binary
- dfs
- recursive
- binary search
- 미디움
- string
- 중간
- Medium
- binary tree
- backtracking
- hash table
- leetcode
- linked list
- tree
- 이진트리
- 재귀
- Depth-first Search
- easy
- 쉬움
- HashTable
- two pointers
- math
Archives
- Today
- Total
부부의 코딩 성장 일기
LeetCode 58(Length of Last Word, Python) 본문
1. 문제 링크
2. 문제 설명
- 단어와 공백으로 구성된 문자열 s가 주어졌을 때, 가장 마지막 단어의 길이를 반환
- 예시) s = "Hello World", output: 5 (마지막 단어인 "World"의 길이 5 반환)
3. 처음 풀이
- 문자열에 대한 관련 함수를 이미 알고 있어서, 간단하게 해결.
- s의 양쪽 공백을 없애고, ' ' 기준 split을 한 후, 마지막 element의 lenght를 반환
class Solution:
def lengthOfLastWord(self, s: str) -> int:
return len(s.strip().split(' ')[-1]) # 양 쪽 공백을 없애고, ' '기준으로 split 한 후, 마지막 단어의 length를 반환
- 돌릴 때마다 runtime이 달라지긴 했는데, 상위 runtime도 위와 동일하게 품. (별도 알고리즘이 있진 않아보였다.)
4. 다른 풀이
- strip, split을 사용하지 않은 풀이
class Solution:
def lengthOfLastWord(self, s: str) -> int:
s=s[::-1] # 문자열을 거꾸로 뒤집은 뒤,
check=0
while check==0:
if s[0]==' ':
s=s.replace(' ','',1) # 제일 앞의 공백만 제거하는 걸 반복하여 공백 제거
else :
check=1
try:
s.index(' ') # 처음으로 ' '가 등장한 index를 찾아낸 후,
return s.index(' ') # 해당 index를 반환
except:
return len(s) # 공백이 없는 case는 s의 길이를 반환
5. 배운 점
- replace에 3번째 parameter는 바꿀 횟수를 의미함 (ex.replace(' ' ,'',1))
'Algorithm > LeetCode' 카테고리의 다른 글
LeetCode 67(Add Binary, Python) (0) | 2023.11.09 |
---|---|
LeetCode 66(Plus One, Python) (0) | 2023.11.08 |
LeetCode 35(Search Insert Position, Python) (0) | 2023.11.06 |
LeetCode 26(Remove Duplicates from Sorted Array, Python) (0) | 2023.11.05 |
LeetCode 27(Remove Element, Python) (0) | 2023.11.04 |