Question
Given a string, find out if its characters can be rearranged to form a palindrome.
Example
For
inputString = "aabb"
, the output should bepalindromeRearranging(inputString) = true
.We can rearrange
"aabb"
to make"abba"
, which is a palindrome.
Input/Output
[execution time limit] 4 seconds (py3)
[input] string inputString
A string consisting of lowercase English letters.
Guaranteed constraints:
1 ≤ inputString.length ≤ 50
.[output] boolean
true
if the characters of theinputString
can be rearranged to form a palindrome,false
otherwise.
Best_ANSWER
def palindromeRearranging(inputString):
return sum([inputString.count(i)%2 for i in set(inputString)]) <= 1
palindrome은 거꾸로 읽어도 제대로 읽은 것과 같은 문장이 되는 것을 말한다.
inputString이
"abbcabb"
으로 아무렇게 주어진다고 해도"abbcbba"
의 palindrome의 형태로 만들어 진다면 true이다.처음에는 문장이 홀수인 경우, 짝수인 경우를 나누어 생각한뒤에 input string의 원소가 2로 나누었을 때 나머지가 0인지, 1인지 조건문을 사용하면서 풀어보았다. 하지만 결과는 좋지 못했다.
정답을 보았을 때, 생각보다 간단하게 판단할 수 있음을 알게 되었다.
inputString =
"abbcabb"
을[inputString.count(i)%2 for i in set(inputString)]
을 적용하면[0, 0, 1]
가 출력된다.
만약 inputString =abca
일 경우[1, 1, 0]
하나의 character가 홀수인 경우가 2이면 palindrome이 성립되지 못한다.(여러 예시를 종이에 적어가면서 확인하면 이해하기 쉬움!). 내가 설명한 것들을 이용하여 return한 모습을 위 답변을 통해 볼 수 있다.