
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find one extra character in a string using C++.
Suppose we have two strings S and T, the length of S is n, and the length of T is n + 1. The T will hold all characters that are present in S, but it will hold one extra character. Our task is to find the extra character using some efficient approach.
To solve this problem, we will take one empty hash table, and insert all characters of the second string, then remove each character from the first string, the remaining character is an extra character.
Example
#include<iostream> #include<unordered_map> using namespace std; char getExtraCharacter(string S, string T) { unordered_map<char, int> char_map; for (int i = 0; i < T.length(); i++) char_map[T[i]]++; for (int i = 0; i < S.length(); i++) char_map[S[i]]--; for (auto item = char_map.begin(); item != char_map.end(); item++) { if (item->second == 1) return item->first; } } int main() { string S = "PQRST"; string T = "TUQPRS"; cout << "Extra character: " << getExtraCharacter(S, T); }
Output
Extra character: U
- Related Articles
- Find the first repeated character in a string using C++.
- How to find a unique character in a string using java?
- First non-repeating character using one traversal of string in C++
- Repeating each character number of times their one based index in a string using JavaScript
- C program to remove extra spaces using string concepts.
- Take off last character if a specific one exists in a string?
- Find the index of the first unique character in a given string using C++
- How to find the shortest distance to a character in a given string using C#?
- How to find the longest distance to a character in a given string using C#?
- How to remove a character (‘’) in string array and display result in one string php?
- Remove extra spaces in string JavaScript?
- Find word character in a string with JavaScript RegExp?
- Find repeated character present first in a string in C++
- Balance a string after removing extra brackets in C++
- Find last index of a character in a string in C++

Advertisements