I wrote code to determine if a string is a palindrome of a permutation. This exercise was taken from Cracking the Coding Interview. I'm looking for any tips on improving it.
#include <iostream>
#include <string>
/*
* Determine if a string is a palindrome of a permutation.
* For simplicity, assume each string contains ONLY alphabetical characters.
*/
//strip string of non-alphabetical characters
std::string strip_junk(std::string s){
std::string output("");
for(char& c : s)
if(isalpha(c)){
c = tolower(c);
output += c;
}
return output;
}
//determine how many times each character appears in the string
int *get_char_counts(std::string input){
static const int ascii_sub = 97;
static int counters[26]{0};
for(char c : input){
counters[c - ascii_sub]++; //if c='a', c-ascii_sub = 0. if c='z', c-ascii_sub = 25
}
return counters;
}
//check if more than one character appears an odd number of times
bool check_chars(std::string input){
int *char_counter = get_char_counts(input);
bool flag = false;
for(int i = 0; i < 26; ++i){
if(*(char_counter + i) % 2 != 0){ //if number is odd, check if it appeared twice
if(flag)
return false; //it appeared twice, return false
flag = true;
}
}
return true;
}
//check if string is a palindrome of a permutation
bool palindromePermutation(std::string input){
input = strip_junk(input);
return check_chars(input);
}
int main(void){
std::string input;
std::getline(std::cin, input);
std::cout << (palindromePermutation(input) ? "True" : "False") << std::endl;
}
tolower(c);
looks broken. You probably intended it to bec=tolower(c);
instead.tolower
doesn't modify its argument--it just returns the lower-case equivalent. \$\endgroup\$