The problem I want to solve is very simple:
Given a string s and a string t, check if s is subsequence of t. there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100).
Example 1: s = "abc", t = "ahbgdc" Return true.
Example 2: s = "axc", t = "ahbgdc" Return false.
I only learnt C++ for about 30 hours, so I am not sure whether my below solution is correct C++ style or not, especially when to free the pointer allocated space. I assigned two char pointer to each string and I do know I need to free them somewhere else. Since the return value depends on pointer, I don't know where to free the pointer allocated memory, which should be a big deal.
What I thought about this question is that there must be two pointers, each pointing one string. For these two strings, using pointers to compare character one by one.
#include <iostream> #include <string.h> using namespace std; class Solution { public: bool isSubsequence(string s, string t) { char *sPtr = new char[s.size() + 1]; char *tPtr = new char[t.size() + 1]; bool returnVal = false; strcpy(sPtr, s.c_str()); strcpy(tPtr, t.c_str()); while (*sPtr && *tPtr){ if (*sPtr == *tPtr++) { sPtr++; } } return !*sPtr; } }; int main() { string s = "abc"; string t = "ahbgdc"; Solution sol = Solution(); cout << sol.isSubsequence(s, t)<<endl; return 0; }
After I talked to one of classmates, he suggests that to include and use c++ string class to do this question. Following is my solution followed his suggestion, but for my above solution, he just said "I don't know dude, I just use c++ string class, that's simple. Your solution is just weird to me but I don't know why I feel weird."
class Solution { public: bool isSubsequence(string s, string t) { int sIndex = 0; int tIndex = 0; while (sIndex < s.size() && tIndex < t.size()) { if (s[sIndex] == t[tIndex++]) { sIndex++; } } return sIndex >= s.size(); } };