Find if an array contains a string with one mismatch in C++


Suppose we have a string s, and another array of strings A. We have to find whether the array is containing a string with the one-character difference from the current string of different lengths. Suppose the string is like “banana”, and the array looks like [“bana”, “orange”, “banaba”, “banapy”], the result will be true, as there is one string banaba, here only one character is different than a banana.

To solve this problem, we will follow some steps −

  • Traverse through given string s, and check for every string in the array, then follow these steps for every string in arr −

    • Check if the string in arr has the same length with the string s

    • If the lengths are the same, then check whether there is any single character mismatch or not, if yes, then return true, otherwise false.

Example

 Live Demo

#include<iostream>
#include<vector>
using namespace std;
bool hasOneCharMismatch(vector<string>arr, string s) {
   int n = arr.size();
   if (n == 0)
      return false;
   for (int i = 0; i < n; i++) {
      if (arr[i].size() != s.size())
         continue;
      bool difference = false;
      for (int j = 0; j < (int)arr[i].size(); j++) {
         if (arr[i][j] != s[j]) {
            if (!difference)
               difference = true;
            else {
               difference = false;
               break;
            }
         }
      }
      if (difference)
         return true;
   }
   return false;
}
int main() {
   vector<string> arr;
   arr.push_back("bana");
   arr.push_back("orange");
   arr.push_back("banaba");
   arr.push_back("banapy");
   if(hasOneCharMismatch(arr, "banana")){
      cout << "One character mismatch found";
   }
   else{
      cout << "One character mismatch not found";
   }
}

Output −

One character mismatch found

Updated on: 19-Dec-2019

98 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements