How to check whether the letters of a string exist in the given order within another string?

I'm trying to make a program to check whether the word "nadia" is present with this sequence in a string. if you can delete zero or more characters to get this word then you should print "YES" else print "NO". Can anyone help me find what are the test cases that I am missing? When I try to submit it, it says wrong output.

Here's my code:

#include <iostream> #include <stdlib.h> #include <string> #include <vector> using namespace std; bool nadiaFound(string s){ int counter = 0; char key[5] = { 'n', 'a', 'd', 'i', 'a' }; for (int i = 0; i < s.size(); i++){ if (s[i] == key[counter]){ counter++; } } if (counter == 5){ return true; } else { return false; } } int main(){ int T; cin >> T; string *names = new string[T]; for (int i = 0; i < T; i++){ cin >> names[i]; } bool *barr = new bool[T]; for (int i = 0; i < T; i++){ barr[i] = false; } for (int i = 0; i < T; i++){ if (nadiaFound(names[i])){ barr[i] = true; } else{ barr[i] = false; } } for (int i = 0; i < T; i++){ if (barr[i]){ cout << "YES" << endl; } else { cout << "NO" << endl; } } return 0; }

--------------Solutions-------------

You may access out of bound memory while accessing key[counter] causing undefined behaviour. One possible fix is:

for (int i = 0; i < s.size(); i++){
if (s[i] == key[counter]){
if(++counter == 5) break;
// ^^ ^^^^ ^^^^^
}
}

or rewrite for as for (int i = 0; i < s.size() && counter < 5; i++)

This can also work:

#include <iostream>
#include <string>
using namespace std;

int main(){
string names;
getline(cin,names);
cout << names << endl;
if (names.find("a", names.find("i", names.find("d", names.find("a", names.find("n", 0))))) != string::npos)
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
}

The result returned by the functions find points to the first location within the string where the searched string begins or where the searched char is located (depending on the variant).

If the search failed, both functions return a special value denoted as string::npos (This value, when used as the value for a len (or sublen) parameter in string's member functions, means "until the end of the string".). You can use it to check if your haystack contained the desired find.

Category:c# Time:2018-12-19 Views:4
Tags: algorithm

Related post

Copyright (C) pcaskme.com, All Rights Reserved.

processed in 0.491 (s). 13 q(s)