Check whether two strings contain same characters in same order
Problem
You are given 2 strings. Let's call them s1 and s2. Your task is to find out wheahter these two strings, contain same characters in same order or not. Means, HackersFriend has same occurance of words as HHackerssFrriend have. Have a look at example.
Example
Input 1
s1 = "HackersFriend"
s2 = "HackersssFriend"
Output 1
YES
Input 2
s1 = "HackerFriend"
s2 = "HackersFriend"
Output 2
NO
Solution
Key idea here is to remove duplicates from each string and match if they are same. If they are same we will say YES otherwise we will say NO. Which means, suppose we have a word like HackersssFriend. Here we, have s 3 times, we will change it to 1 time, i.e string will become HackersFriend.
Here is implementation of this idea.
#include <bits/stdc++.h>
using namespace std;
string getString(char x)
{
// string class has a constructor
// that allows us to specify size of
// string as first parameter and character
// to be filled in given size as second
// parameter.
string s(1, x);
return s;
}
// Function that returns true if
// the given strings contain same
// characters in same order
bool areSame(string s1, string s2)
{
// Get the first character of both strings
string a = getString(s1[0]), b = getString(s2[0]);
// Now if there are adjacent similar character
// remove that character from s1
for (int i = 1; i < s1.length(); i++)
if (s1[i] != s1[i - 1]) {
a += getString(s1[i]);
}
// Now if there are adjacent similar character
// remove that character from s2
for (int i = 1; i < s2.length(); i++)
if (s2[i] != s2[i - 1]) {
b += getString(s2[i]);
}
// If both the strings are equal
// then return true
if (a == b)
return true;
return false;
}
// Main Function
int main()
{
string s1 = "HackersssFriend", s2 = "HackersFriend";
if (areSame(s1, s2))
cout << "Yes";
else
cout << "No";
return 0;
}
YES