diff options
Diffstat (limited to 'top-interview-questions/easy/strings')
3 files changed, 77 insertions, 0 deletions
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 @@ | |||
1 | class Solution { | ||
2 | public: | ||
3 | int firstUniqChar(string s) { | ||
4 | int count[256] = {}; | ||
5 | |||
6 | for (char c : s) { | ||
7 | count[c]++; | ||
8 | } | ||
9 | |||
10 | for (size_t i = 0; i < s.size(); ++i) { | ||
11 | if (count[s[i]] == 1) { | ||
12 | return i; | ||
13 | } | ||
14 | } | ||
15 | |||
16 | return -1; | ||
17 | } | ||
18 | }; | ||
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 @@ | |||
1 | class Solution { | ||
2 | public: | ||
3 | static void count(const string& s, int* counts) { | ||
4 | for (char c : s) { | ||
5 | counts[c]++; | ||
6 | } | ||
7 | } | ||
8 | |||
9 | bool isAnagram(string s, string t) { | ||
10 | if (s.size() != t.size()) { | ||
11 | return false; | ||
12 | } | ||
13 | // strings are equal length | ||
14 | |||
15 | int sCount[256] = {}; | ||
16 | int tCount[256] = {}; | ||
17 | |||
18 | count(s, sCount); | ||
19 | count(t, tCount); | ||
20 | |||
21 | for (char c : s) { | ||
22 | if (sCount[c] != tCount[c]) { | ||
23 | return false; | ||
24 | } | ||
25 | } | ||
26 | |||
27 | return true; | ||
28 | } | ||
29 | }; | ||
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 @@ | |||
1 | class Solution { | ||
2 | public: | ||
3 | bool IsAlphaNum(char c) { | ||
4 | return | ||
5 | (('a' <= c) && (c <= 'z')) || | ||
6 | (('A' <= c) && (c <= 'Z')) || | ||
7 | (('0' <= c) && (c <= '9')); | ||
8 | } | ||
9 | |||
10 | void Transform(string& s) { | ||
11 | size_t j = 0; | ||
12 | for (size_t i = 0; i < s.size(); ++i) { | ||
13 | if (IsAlphaNum(s[i])) { | ||
14 | s[j] = std::tolower(s[i]); | ||
15 | j++; | ||
16 | } | ||
17 | } | ||
18 | s.resize(j); | ||
19 | } | ||
20 | |||
21 | bool isPalindrome(string s) { | ||
22 | Transform(s); | ||
23 | for (size_t i = 0; i < s.size()/2; ++i) { | ||
24 | if (s[i] != s[s.size()-i-1]) { | ||
25 | return false; | ||
26 | } | ||
27 | } | ||
28 | return true; | ||
29 | } | ||
30 | }; | ||