String scans
These palindrome examples compare literal ASCII characters. Normalize first only when the task defines a normalization rule.
| Palindrome | O(n) time | Opposing endpoints |
| Anagram count | O(n + m) expected time | Compare counts and lengths |
| Common prefix | O(total characters) upper bound | Stop at first mismatch |
| KMP search | O(n + m) time | m-entry prefix table for the pattern |
Python
def palindrome(s):
i, j = 0, len(s) - 1
while i < j:
if s[i] != s[j]: return False
i, j = i + 1, j - 1
return TrueC++
bool palindrome(const std::string& s) {
for (size_t i = 0; i < s.size()/2; ++i)
if (s[i] != s[s.size()-1-i]) return false;
return true;
}Java
static boolean palindrome(String s) {
for (int i = 0; i < s.length()/2; i++)
if (s.charAt(i) != s.charAt(s.length()-1-i)) return false;
return true;
}