Optimize c/isogram/is_isogram to use map, not inner loop
This commit is contained in:
+8
-14
@@ -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;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user