백준 오랜만에 풀어봤는데.. 1316번이 젤 푼 사람이 많아서 도전! 해봤는데 실패했다.
n = int(input())
sum = 0
def groupWord(str):
sumstrcnt = 0
flag = 0
maxstrcnt = 0
for j in range(len(str)):
strcnt = str.count(str[j]) #str 문자열 내에서 찾을 값의 개수
if strcnt == len(str): #aaa 처럼 한 문자가 문자열 전체인 경우
return 1
if maxstrcnt < strcnt:
maxstrcnt = strcnt
sumstrcnt += strcnt
if sumstrcnt == len(str): #abcde 처럼 모든 문자가 다른 경우
return 1
for j in range(len(str)):
spacing = str.rindex(str[j]) - str.index(str[j])
for k in range(j+1, j + spacing + 1):
if j+spacing+1 >= len(str):
break
if str[j] == str[k]:
flag += 1
else:
if str[j] == str[k-1]:
flag += 0
else:
flag -= 1
if flag >= 1:
return 1
else:
return 0
for i in range(n):
str = input()
sum += groupWord(str)
print(sum)
참고로 이 코드는 내가 풀다가 도저히 아이디어가 떠오르지 않아 포기했다.
복잡하게 풀고싶지 않아 간결한 코드를 생각하다보니 테스트 예제가 하나는 되고, 하나는 안되고 하는 상황이 반복됐다.
3시간동안 붙잡고 있어서 결국 구글링했다.
그런데 웬걸.. 10줄로 풀 수 있는 문제였잖아!!!!
n = int(input())
group_word = n
for i in range(n):
str = input()
for j in range(len(str) - 1):
if str[j] == str[j+1]:
continue
elif str[j] in str[j+1 :]:
#이 부분이 중요!! 연속된 글자가 다른 글자인데
#그 이후 같은 글자가 문자열에 존재한다면 그것은 그룹 단어가 아니므로 -1
group_word -= 1
break
print(group_word)
문자열 in 문자열이라는 내장 함수를 몰랐다..
그리고 [j+1 : ] 처럼 편하게 인덱스를 지정해 줄 수 있지만, 나는 c언어에 익숙하다보니 이를 활용할 수 있을거라고 상상도 못했다.
또한 문제를 풀 만한 아이디어도 효율적이지 못한 것 같아서 자괴감이 들었다.
그래도 이번 기회로 한 걸음 더 성장했으니까!! 3시간 투자한거로도 만족한다.
함수를 정리하지 않고 간다면 내 것으로 만들 수 없겠지?!
in
in은 찾고자 하는 문자가 원래 문자열에 포함되어있는지 여부를 boolean 자료형으로 리턴
str = "findletter"
print("d" in str) #True
print("s" in str[1:]) #False
find()
find()는 찾고자하는 문자열 위치를 인덱스 값 int 자료형으로 리턴
str = "findletter"
print(str.find("d")) #3
- find() 함수는 문자열의 앞에서부터 값을 찾아서 반환하기 때문에, 찾고자 하는 문자열이 여러개가 있더라도 하나의 인덱스만 반환한다.
- find() 함수를 사용해 문자열에 포함되어있지 않은 값을 찾으면 -1을 리턴한다.
index()
find()와 기능은 같지만, 찾는 문자열이 없으면 index()는 ValueError가 발생한다.
rfind(), rindex()
찾으려는 문자열의 인덱스를 뒤에서부터 탐색한다.
startswith
특정 문자열로 시작하면 True, 아니면 False
str = "this is python"
str.startswith("this") #True
str.startswith("python") #False
endswith
특정 문자열로 끝나면 True, 아니면 False
str = "this is python"
str.endswith("this") #False
str.endswith("python") #True
문자열 찾는 함수도 알아봤으니 나중에 다시 1316번 도전~~!!
파이썬에서 문자열을 다루는 함수를 더 공부해야겠다!
'Algorithm' 카테고리의 다른 글
[11650, 11651] 파이썬 한 줄 입력받기 (0) | 2024.07.10 |
---|---|
[1193] 분수찾기 (0) | 2024.07.09 |
[1181] 문자열 리스트 정렬, 중복 제거 (0) | 2024.07.08 |
[4673] 재귀함수를 사용한 셀프넘버 (0) | 2024.07.05 |
파이썬 기본 문법 정복하기! / C언어랑 파이썬 비교 (2) | 2024.02.19 |