Check If a String Can Break Another String in C++


Suppose we have two strings s1 and s2 whose size are same; we have to check whether some permutation of string s1 can break some permutation of string s2 or vice-versa. A string a can break string b if x[i] >= y[i] (in alphabetical order) for all i in range 0 to n-1.

So, if the input is like s1 = abc and s2 = xya, then the output will be true. This is because "ayx" is a permutation of s2 that can break to string "abc" which is a permutation of s1="abc".

To solve this, we will follow these steps −

  • Define a function check(), this will take s1, s2,

  • for initialize i := 0, when i < size of s1, update (increase i by 1), do −

    • if s2[i] < s1[i], then −

      • return false

  • return true

  • From the main method, do the following −

  • sort the array s1

  • sort the array s2

  • f3 := check(s2, s1)

  • f4 := check(s1, s2)

  • return true either f3 is true or f4 is true, otherwise false

Example 

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   bool check(string& s1, string& s2){
      for (int i = 0; i < s1.size(); i++) {
         if (s2[i] < s1[i])
            return false;
      }
      return true;
   }
   bool checkIfCanBreak(string s1, string s2) {
      sort(s1.begin(), s1.end());
      sort(s2.begin(), s2.end());
      bool f3 = check(s2, s1);
      bool f4 = check(s1, s2);
      return f3 || f4;
   }
};
main(){
   Solution ob;
   cout << (ob.checkIfCanBreak("abc", "xya"));
}

Input

"abc", "xya"

Output

1

Updated on: 17-Nov-2020

149 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements