 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements
 