코딩
[Python/Algorithm] list의 첫 번째 요소와 마지막 요소가 같은지 확인 후 조작
청담동최사장
2017. 2. 17. 13:37
1. 문제
You are given a string. Remove its first and last characters until the string is empty or the first and the last characters are not equal. Output the resulting string.
Example
For
inputString = "abacaba"
, the output should bereduceString(inputString) = ""
.Explanation:
"bacab" -> "aca" -> "c" -> ""
.For
inputString = "12133221"
, the output should bereduceString(inputString) = "1332"
.
2. 문제풀이
1) 첫 번째 요소와 마지막 요소가 같은지 확인한다.
2) 같다면 지워버리고, 다르다면 바로 출력한다.
3) 계속 지워서 len(list)가 1이거나 0이면 멈춘다.
3. 해답
def reduceString(inputString):
lst = list(inputString)
while len(lst) >= 2 and lst[0] == lst[-1]:
del lst[0]
del lst[-1]
if len(lst) ==1:
lst = []
break
return ''.join(lst)
4. 실수요소
- 매 리스트가 삭제 될 때 마다 len(list)가 변하므로 index에 주의한다.
5. 기억해둘 요소
- 리스트의 마지막 요소를 선택하기 위해서는 list[-1]이 가능하다.