Find the last non repeating character in string in C++


Suppose we have a string str. We have to find the last non-repeating character in it. So if the input string is like “programming”. So the first non-repeating character is ‘n’. If no such character is present, then return -1.

We can solve this by making one frequency array. This will store the frequency of each of the character of the given string. Once the frequency has been updated, then start traversing the string from the last character one by one. Then check whether the stored frequency is 1 or not, if 1, then return, otherwise go for previous character.

Example

#include <iostream>
using namespace std;
const int MAX = 256;
static string searchNonrepeatChar(string str) {
   int freq[MAX] = {0};
   int n = str.length();
   for (int i = 0; i < n; i++)
      freq[str.at(i)]++;
   for (int i = n - 1; i >= 0; i--) {
      char ch = str.at(i);
      if (freq[ch] == 1) {
         string res;
         res+=ch;
         return res;
      }
   }
   return "-1";
}
int main() {
   string str = "programming";
   cout<< "Last non-repeating character: " << searchNonrepeatChar(str);
}

Output

Last non-repeating character: n

Updated on: 18-Dec-2019

184 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements