I’m starting to learn C++
by doing a lot of exercises, and I need your help so I can improve,
Here is how it goes, I will try to solve an exercise and post both the exercise and my solution to it,
And I want you to point me to where / what improvements I can do to make my code better, this would help me both uncover missing parts that I didn’t know about, and better ways of coding, alternative coding style or features introduced in C++11 C/++14/C++17/C++20 are welcomed to be mentioned, with some code snippet if possible, as I'm trying to write some modern C++ as possible while learning, it help in adopting as a habit.
Here it is
Given a string, write a function to check if it is a permutation of a palindrome. A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters.
Here is my solution
#include <iostream>
#include <string>
#include <cassert>
#include <vector>
#include <unordered_map>
bool isPalinStr(const std::string& a) {
std::unordered_map<char, int> x;
if (a.length() % 2 == 0) {
for (int i = 0; i != a.length(); ++i) {
x[a[i]] += 1;
}
for (auto& ch : x) {
if (ch.second % 2 != 0)
return false;
else {
return true;
}
}
}
else {
for (int i = 0; i != a.length(); ++i) {
x[a[i]] += 1;
}
unsigned even = 0;
unsigned odd = 0;
for (auto& ch : x) {
if (ch.second % 2 == 0)
even++;
else {
odd++;
}
}
if (even % 2 == 0 && odd == 1) {
return true;
}
else {
return false;
}
}
}
int main() {
assert(true == isPalinStr("aabbccd"));
assert(false == isPalinStr("aabbcd"));
return 0;
}
Hey reader you might want to check other parts :