
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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