C++ MyProgrammingLab problem: Implement the function below //return true iff the
ID: 3562620 • Letter: C
Question
C++ MyProgrammingLab problem:
Implement the function below
//return true iff the letters in s form a subset of the letters in t .
// e.g. "bbcaca", "abba","bcda", "dd" and "bbbaaaa" are subsets of "abcd".
// Unlike for bags, we care only if a letter occurs in the word, not how many times it occurs.
// For example, if you want to find a word s that only contains vowels you could check whether s is a subset of "aeiou". Using the words.txt file and minimum length 3, you would get five hits: "aia", "eau", "euoi", "euouae" and "iou".
//precondition: s and t contain only lowercase letters {'a'... 'z'}
bool isSubSet(const string &s, const string &t) ;
Do not write the entire program or any other functions.
Here is my solution:
bool isSubSet(const string &s, const string &t)
{
int i = 0, j = 0;
int k = s.length()-1;
while(t[i])
{
if(t[i] == s[j])
{
i++;
j++;
}
else
{
i++;
}
}
if(j == k)
{
return true;
}
else
{
return false;
}
}
MyProgrammingLab is not accepting this answer: It also gave me some hints that I should consider:
? You almost certainly should be using: '
? You almost certainly should be using: a
? You almost certainly should be using: for
Can someone post the correct solution for this problem?
Explanation / Answer
// Check working code sample here: http://ideone.com/jcR59a
bool isSubSet(const string &s, const string &t)
{
int diff_s[26] = {0};
int diff_t[26] = {0};
for(int i=0; i<t.length(); i++)
diff_t[t[i]-'a']++;
for(int i=0; i<s.length(); i++) {
if(diff_t[s[i]-'a']==0)
return false;
}
return true;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.