From 4689e4e80b479be25f7557d05818f5caa723aafa Mon Sep 17 00:00:00 2001 From: 3gg <3gg@shellblade.net> Date: Wed, 5 Feb 2025 18:36:31 -0800 Subject: Initial commit. --- .../easy/strings/03_first_unique_character.cc | 18 +++++++++++++ .../easy/strings/04_valid_anagram.cc | 29 +++++++++++++++++++++ .../easy/strings/05_valid_palindrome.cc | 30 ++++++++++++++++++++++ 3 files changed, 77 insertions(+) create mode 100644 top-interview-questions/easy/strings/03_first_unique_character.cc create mode 100644 top-interview-questions/easy/strings/04_valid_anagram.cc create mode 100644 top-interview-questions/easy/strings/05_valid_palindrome.cc (limited to 'top-interview-questions/easy/strings') diff --git a/top-interview-questions/easy/strings/03_first_unique_character.cc b/top-interview-questions/easy/strings/03_first_unique_character.cc new file mode 100644 index 0000000..871f761 --- /dev/null +++ b/top-interview-questions/easy/strings/03_first_unique_character.cc @@ -0,0 +1,18 @@ +class Solution { +public: + int firstUniqChar(string s) { + int count[256] = {}; + + for (char c : s) { + count[c]++; + } + + for (size_t i = 0; i < s.size(); ++i) { + if (count[s[i]] == 1) { + return i; + } + } + + return -1; + } +}; diff --git a/top-interview-questions/easy/strings/04_valid_anagram.cc b/top-interview-questions/easy/strings/04_valid_anagram.cc new file mode 100644 index 0000000..3ca6b7c --- /dev/null +++ b/top-interview-questions/easy/strings/04_valid_anagram.cc @@ -0,0 +1,29 @@ +class Solution { +public: + static void count(const string& s, int* counts) { + for (char c : s) { + counts[c]++; + } + } + + bool isAnagram(string s, string t) { + if (s.size() != t.size()) { + return false; + } + // strings are equal length + + int sCount[256] = {}; + int tCount[256] = {}; + + count(s, sCount); + count(t, tCount); + + for (char c : s) { + if (sCount[c] != tCount[c]) { + return false; + } + } + + return true; + } +}; diff --git a/top-interview-questions/easy/strings/05_valid_palindrome.cc b/top-interview-questions/easy/strings/05_valid_palindrome.cc new file mode 100644 index 0000000..1b4ca6f --- /dev/null +++ b/top-interview-questions/easy/strings/05_valid_palindrome.cc @@ -0,0 +1,30 @@ +class Solution { +public: + bool IsAlphaNum(char c) { + return + (('a' <= c) && (c <= 'z')) || + (('A' <= c) && (c <= 'Z')) || + (('0' <= c) && (c <= '9')); + } + + void Transform(string& s) { + size_t j = 0; + for (size_t i = 0; i < s.size(); ++i) { + if (IsAlphaNum(s[i])) { + s[j] = std::tolower(s[i]); + j++; + } + } + s.resize(j); + } + + bool isPalindrome(string s) { + Transform(s); + for (size_t i = 0; i < s.size()/2; ++i) { + if (s[i] != s[s.size()-i-1]) { + return false; + } + } + return true; + } +}; -- cgit v1.2.3