Optimize c/isogram/is_isogram to use map, not inner loop

This commit is contained in:
dwrz
2019-02-24 12:59:43 +00:00
parent c5d1d0199b
commit 37181b0c19
+8 -14
View File
@@ -33,21 +33,15 @@ bool is_symbol_char(char c) {
bool is_isogram(const char phrase[]) { bool is_isogram(const char phrase[]) {
if (phrase == NULL) { return false; } if (phrase == NULL) { return false; }
if (length(phrase) == 0) { return true; } if (length(phrase) == 0) { return true; }
// Lowercase the phrase. // There are 26 lowercased ASCII alpha chars.
// We make a copy, since the input is constant. // We can use 26 indexes to keep track of each one.
char lower_phrase[(length(phrase))]; char char_map[26] = { 0 };
copy_phrase(phrase, lower_phrase); for (int i = 0; i < length(phrase); i++) {
lowercase_phrase(lower_phrase); if (is_symbol_char(phrase[i])) { continue; } // Ignore non-alpha chars.
// Check if the lowercased phrase is an isogram. if (char_map[lowercase(phrase[i]) - 97] != 0) {
for (int i = 0; i < length(lower_phrase); i++) { return false;
if (is_symbol_char(lower_phrase[i])) { continue; } // Ignore non-alpha chars.
for (int j = 0; j < length(lower_phrase); j++) {
if (is_symbol_char(lower_phrase[j])) { continue; }
if (j == i) { continue; }
if (lower_phrase[i] == lower_phrase[j]) {
return false;
}
} }
char_map[lowercase(phrase[i]) - 97]++;
} }
return true; return true;
} }