일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- 백준
- leetcode
- ChatGPT
- 편스토랑 우승상품
- Git
- 더현대서울 맛집
- 프로그래머스 파이썬
- 금융문자분석경진대회
- hackerrank
- github
- ubuntu
- 코로나19
- SW Expert Academy
- PYTHON
- 자연어처리
- Baekjoon
- AI 경진대회
- 맥북
- Docker
- gs25
- dacon
- 데이콘
- 프로그래머스
- 편스토랑
- programmers
- 캐치카페
- Kaggle
- Real or Not? NLP with Disaster Tweets
- 우분투
- 파이썬
- Today
- Total
솜씨좋은장씨
[leetCode] 2490. Circular Sentence (Python) (feat.ChatGPT) 본문
[leetCode] 2490. Circular Sentence (Python) (feat.ChatGPT)
솜씨좋은장씨 2023. 3. 27. 15:27
코딩 1일 1문제! 오늘의 문제는 leetCode 의 Circular Sentence 입니다.
Circular Sentence - LeetCode
Can you solve this real interview question? Circular Sentence - A sentence is a list of words that are separated by a single space with no leading or trailing spaces. * For example, "Hello World", "HELLO", "hello world hello world" are all sentences. Words
leetcode.com
👨🏻💻 문제 풀이
단어 2개씩 짝 지은 후 반복문을 돌면서
단어의 맨 뒷 글자와 맨 앞 글자를 비교해서 다른 경우 정답을 Fasle 로 바꾸고 반복문을 종료하고
그렇지 않은 경우 모든 반복문이 끝날때까지 기다렸다가 정답을 True 로 return 하는 식으로 문제를 풀었습니다.
👨🏻💻 코드 ( Solution ) - SOMJANG
class Solution:
def isCircularSentence(self, sentence: str) -> bool:
is_circular = True
word_list = sentence.split()
for idx in range(len(word_list) - 1):
if word_list[idx][-1] != word_list[idx+1][0]:
is_circular = False
break
if word_list[-1][-1] != word_list[0][0]:
is_circular = False
return is_circular

👨🏻💻 코드 ( Solution ) - ChatGPT - 1회차
class Solution:
def isCircularSentence(self, sentence: str) -> bool:
words = sentence.split()
n = len(words)
for i in range(n):
if words[i][-1] != words[(i+1)%n][0]:
return False
return True

ChatGPT 에게 문제를 풀어달라고 하니 저와 같은 방식인데
한가지 달랐던 것이 마지막 단어와 첫번째 단어를 따로 if 조건문으로 체크하지 않고
% 를 활용하여 그대로 반복문을 돌면서 체크하도록 해서 푼 것이었습니다.
딱 보고 아 ! 저걸 왜 생각못했지! 라는 생각이 들었습니다.
하지만 이렇게 풀었을때는 크게 달라지는게 없으니 더 최적화 된 코드를 부탁했습니다.
👨🏻💻 코드 ( Solution ) - ChatGPT - 2회차 ( 최적화된 코드를 부탁해! - 하지만 실패 케이스 존재 )
class Solution:
def isCircularSentence(self, sentence: str) -> bool:
words = sentence.split()
n = len(words)
last_chars = {words[i][-1]: i for i in range(n)}
if words[0][0] not in last_chars:
return False
curr = last_chars[words[0][0]]
for i in range(n-1):
next = (curr+1) % n
if words[next][0] not in last_chars or last_chars[words[next][0]] != curr:
return False
curr = next
return True

👨🏻💻 코드 ( Solution ) - ChatGPT - 3회차 ( 특정 실패 케이스 알려주고 다시 부탁 )
class Solution:
def isCircularSentence(self, sentence: str) -> bool:
words = sentence.split()
n = len(words)
counts = {}
for word in words:
if word[0] == word[-1]:
counts[word[0]] = counts.get(word[0], 0) + 1
return sum(counts.values()) == n
GitHub - SOMJANG/CODINGTEST_PRACTICE: 1일 1문제 since 2020.02.07
1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.
github.com