Find duplicate string


#1

Given an array of strings in which some strings are repeated,find the first repeating string


Given an array of strings find the first pair of string which is repeated
#2

#include <bits/stdc++.h>
using namespace std;
int main(){
string arr[]={“name”,“class”,“address”,“class”,“name”,“anshika”,“city”};
int n=7;
int hash[7];
for(int i=0;i<n;i++)
hash[i]=0;
unordered_map<string ,int> strings;
for(int i=0;i<n;i++){
if(strings.find(arr[i])!=strings.end())
strings[arr[i]]+=1;
else
strings.insert(make_pair(arr[i],1));
}
for(int i=0;i<n;i++){
if(strings[arr[i]]>1){
cout<<arr[i];
break;
}
}
}


#3

#include
using namespace std;

// returns first repeated word
string findFirstRepeated(string s)
{
// break string into tokens
// and then each string into set
// if a word appeared before appears
// again, return the word and break

istringstream iss(s);
string token;

// hashmap for storing word and its count
// in sentence
unordered_map<string, int> setOfWords;

// store all the words of string
// and the count of word in hashmap

while (getline(iss, token, ' ')) {
    if (setOfWords.find(token) != setOfWords.end())             
        setOfWords[token] += 1;  // word exists
    else
        // insert new word to set
        setOfWords.insert(make_pair(token, 1));        
}

// traverse again from first word of string s
// to check if count of word is greater than 1

// either take a new stream or store the words 
// in vector of strings in previous loop
istringstream iss2(s);
while (getline(iss2, token, ' ')) {
    int count = setOfWords[token];
    if (count > 1) {
        return token;
    }
}

return "NoRepetition";

}

// driver program
int main()
{
string s(“Ravi had been saying that he had been there”);
string firstWord = findFirstRepeated(s);
if (firstWord != “NoRepetition”)
cout << "First repeated word :: "
<< firstWord << endl;
else
cout << “No Repetitionn”;
return 0;
}


#4

// CPP program to find the first
// repeated character in a string
#include <bits/stdc++.h>
using namespace std;

// Returns first repeating character in str.
char firstRepeating(string &str)
{
// Creates an empty hashset
unordered_set h;

// Traverse the input array from left to right
for (int i=0; i<str.length(); i++)
{
    char c = str[i];

    // If element is already in hash set, update x
    // and then break
    if (h.find(c) != h.end())
        return c;

    else // Else add element to hash set
        h.insert(c);
}

// If there was no repeated character
return '\0';

}

// Driver method to test above method
int main ()
{
string str = “geeksforgeeks”;
cout << firstRepeating(str);
return 0;
}


#5

how to do without using any inbuilt data structure and just using array