- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if characters of a given string can be rearranged to form a palindrome in Python
Suppose we have a string s, we have to check whether characters of the given string can be shuffled to make a palindrome or not.
So, if the input is like s = "raaecrc", then the output will be True as we can rearrange this to "racecar" which is a palindrome.
To solve this, we will follow these steps −
- freq := a map to store all characters and their frequencies in s
- odd_count := 0
- for each element i in the list of all values of freq, do
- if i is odd, then
- odd_count := odd_count + 1
- if odd_count > 1, then
- return False
- if i is odd, then
- return True
Let us see the following implementation to get better understanding −
Example
from collections import defaultdict def solve(st) : freq = defaultdict(int) for char in st : freq[char] += 1 odd_count = 0 for i in freq.values(): if i % 2 == 1: odd_count = odd_count + 1 if odd_count > 1: return False return True s = "raaecrc" print(solve(s))
Input
"raaecrc"
Output
True
Advertisements