Check if a string is a substring of another
Problem
Check if a string is a substring of another string. If true, return the index of the substring’s first letter in the other string. Else, return -1.
Example
input:
abcde cd
abcde cda
abcd de
abcbcde bc
output:
2
-1
-1
1
written in C++
Solution 1
- loop through the string a
- As iterating, check if the current char matches any char of the string b.
- If they do, iterate through the string b along with a to check if all the chars match
Time Complexity = O(n)
int substring(string a, string b){
int result = -1; //result to return
size_t b_ind = 0; //index to iterate through b
for(size_t i = 0; i < a.size(); ++i){
if(b[b_ind] == a[i]){ //if the first char of b matches the char in a
if (b_ind == 0){ //if it is the first letter in b, save it in result
result = (int)i;
}
if (b_ind == b.size() -1){//if all chars in b are in a, return result
return result;
}
++b_ind;//update b_ind to iterate
}else if (b_ind > 0 && a[i-1] == a[i]){ //if b_ind is at 1 and prev char in a equals to the current, cout it as found
if (b_ind == 1){
++result;
}
}else{ //if the chars don't match, reset result and b_ind
if (result != -1){
result = -1;
}
b_ind = 0;
}
}
if (b_ind != b.size()){
result = -1;
}
return result;
}
Solution 2
Use std::string find(string str)
int substring(string a, string b){
size_t found = a.find(b);
if (found == a.npos){
return -1;
}else{
return found;
}
}
Time Complexity = O(n)
Follow-up
What if the string a contains multiple words with space in between and b is a word?
Example
input:
"geeks for geeks" "for"
"geeks for geeks" "sfor"
output:
6
-1
Solution is the same with Solution 2.