Check if a string contains duplicates using std::map - c++

I have a function that checks if a string contains duplicates using std::map by putting each char as a key. Can't figure out why this doesn't work.
#include<iostream>
#include<map>
#include<string>
int unique_char(std::string s){
for(int i=0 ; i < s.size(); i++ )
{
std::map<char,int> uniq_hash_table;
std::pair<std::map<char,int>::iterator,bool> ret;
ret = uniq_hash_table.insert(std::pair<char,int>(s[i],0));
if(ret.second==false)
{
std::cout << "The string contains duplicates" << std::endl;
return 1;
}
}
return 0;
}
int main()
{
std::string s="abcd";
std::string s1="aabc";
if(unique_char(s)==0){
std::cout << "The 1st string does not contain duplicates" << std::endl;}
if(unique_char(s1)==0){
std::cout << "The 2nd string does not contain duplicates" << std::endl;}
return 0;
}
The program returns "string does not contain duplicates" for both examples.
ps: I'm purposely using std::map to get O(n) solution.

Your solution doesn't work because your std::map<char,int> is re-created at each iteration of the loop. Then, at each iteration of the loop, the map is empty. Then, there is no duplication.
Better to use a std::set<char>. You can do something like that :
bool contains_duplicated_char(const std::string& s)
{
std::set<char> check_uniq;
for(unsigned long int i = 0; i < s.length(); ++i)
if(!check_uniq.insert(s[i]).second)
return true; // Duplicated char found
return false; // No duplicated char found
}
and then call it by this way :
const std::string str = "abcdefghijklamnopb";
const bool dupl = contains_duplicated(str);
In order to make your code more generic (managing more data types), you can also create your function in that way :
template <typename Type, typename IteratorType>
bool contains_duplicated(IteratorType begin, IteratorType end)
{
std::set<Type> check_uniq;
for(IteratorType it = begin; it != end; ++it)
if(!check_uniq.insert(*it).second)
return true;
return false;
}
and then call it like :
std::vector<std::string> vec_str;
vec_str.push_back("Foo");
vec_str.push_back("Bar");
vec_str.push_back("Baz");
vec_str.push_back("Bar");
const bool dupl = contains_duplaicated<std::string>(vec_str.begin(), vec_str.end());
//...
const std::string str = "abcdefab";
const bool dupl2 = contains_duplacated<char>(str.begin(), str.end());
//...
const std::deque<long int> x(4, 0);
x[0] = 1;
x[1] = 17;
x[2] = 31;
x[3] = 0;
const bool dupl3 = contains_duplicated<long int>(x.begin(), x.end());

It does not work because uniq_hash_table is recreated for each symbol inside for loop.
Try to move it into the beginning of the function right before the for loop:
std::map<char,int> uniq_hash_table;
for(int i=0 ; i < s.size(); i++ )
{
// ...
}

As your map definition is within the body of the for loop, you recreate an empty map at each iteration.
Declare your container outside the loop and it 'll work better.
Note that you could use a set instead of a map if you never increment the int value.

Related

a runtime error on my leetcode submission :heap use after free on address

#include <bits/stdc++.h>
using namespace std;
#include <unordered_set>
#include <queue>
struct word {
string s;
int level;
word(string a, int b)
: s(a)
, level(b)
{
}
};
bool isadj(string s1, string s2)
{
int len = s1.length(), count = 0;
for (int i = 0; i < len; i++) {
if (s1[i] != s2[i])
count++;
if (count > 1)
return false;
}
return count == 1 ? true : false;
}
int ladderLength(string beginWord, string endWord, vector<string>& wordList)
{
unordered_set<string> st;
for (string s : wordList)
st.insert(s); // adding elements into a set
if (st.find(endWord) == st.end())
return 0;
queue<word> q;
q.push(word(beginWord, 0)); // initialising the queue
while (!q.empty()) {
word temp = q.front(); // pop the current string
q.pop();
if (temp.s == endWord)
return temp.level;
for (auto it = st.begin(); it != st.end(); it++) { // loop over the set to find strings at a distance of 1 and add them to the queue
if (isadj(temp.s, *it)) // i have inserted code here to print the string *it
{
q.push(word(*it, temp.level + 1));
st.erase(*it); // delete the element to avoid looping
}
}
}
return 0;
}
int main()
{
// make dictionary
vector<string> D;
D.push_back("poon");
D.push_back("plee");
D.push_back("same");
D.push_back("poie");
D.push_back("plie");
D.push_back("poin");
D.push_back("plea");
string start = "toon";
string target = "plea";
cout << "Length of shortest chain is: "
<< ladderLength(start, target, D);
return 0;
}
The problem i am trying to solve is https://leetcode.com/problems/word-ladder/
I am unable to trace where I am using a memory that was deallocated again in my program?
The following are my attempts to debug :
I tried to run it on another online ide where the code compiles and runs successfully but gives a wrong answer . in order to debug it I have inserted some lines into my code in order to print all the strings which are at a distance of 1 for my current string. surprisingly an empty string is appearing to be in the set. Please help me in understanding where am I doing a mistake.
unordered_set::erase returns a value, and this returned value is important. You should not ignore it.
In your case, once you erase something from the set, it is invalid. Trying to increment it results in Undefined Behavior.
The correct approach is to replace the current iterator with the returned one, then not increment during the loop.
for (auto it = st.begin(); it != st.end(); )
if (...) {
// ...
it = st.erase(*it);
} else
++it;
After the line:
st.erase(*it); // delete the element to avoid looping
the it iterator is not valid and should not be used.
Your problem seems to be already addressed, but if you'd be interested, this'd also pass without using std::queue, only using std::unordered_set:
// The following block might slightly improve the execution time;
// Can be removed;
static const auto __optimize__ = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(NULL);
std::cout.tie(NULL);
return 0;
}();
// Most of headers are already included;
// Can be removed;
#include <cstdint>
#include <string>
#include <vector>
#include <unordered_set>
#include <algorithm>
using ValueType = std::int_fast16_t;
static const struct Solution {
static const int ladderLength(
const std::string start,
const std::string end,
const std::vector<std::string>& words
) {
std::unordered_set<std::string> words_map(std::begin(words), std::end(words));
std::unordered_set<std::string> head;
std::unordered_set<std::string> tail;
std::unordered_set<std::string>* curr_head;
std::unordered_set<std::string>* curr_tail;
if (words_map.find(end) == std::end(words_map)) {
return 0;
}
head.insert(start);
tail.insert(end);
ValueType ladder = 2;
while (!head.empty() && !tail.empty()) {
if (head.size() < tail.size()) {
curr_head = &head;
curr_tail = &tail;
} else {
curr_head = &tail;
curr_tail = &head;
}
std::unordered_set<std::string> temp_word;
for (auto iter = curr_head->begin(); iter != curr_head->end(); iter++) {
std::string word = *iter;
for (ValueType index_i = 0; index_i < word.size(); index_i++) {
const char character = word[index_i];
for (ValueType index_j = 0; index_j < 26; index_j++) {
word[index_i] = 97 + index_j;
if (curr_tail->find(word) != curr_tail->end()) {
return ladder;
}
if (words_map.find(word) != std::end(words_map)) {
temp_word.insert(word);
words_map.erase(word);
}
}
word[index_i] = character;
}
}
ladder++;
curr_head->swap(temp_word);
}
return 0;
}
};
You might want to break it into more methods, a bit too long for a function.
References
For additional details, please see the Discussion Board where you can find plenty of well-explained accepted solutions with a variety of languages including low-complexity algorithms and asymptotic runtime/memory analysis1, 2.

How to erase element from std::vector<string> by its length(erase not working)

i have given a vector `
vector<string> inputArray = { "aba","aa","ad","vcd","aba" };
and i want to return this vector which contains only string with the longest length, in this case i want to return only {"aba","vcd","aba"}, so for now i want to erase elements which length is not equal to the highest `
vector<string> allLongestStrings(vector<string> inputArray) {
int length = inputArray.size();
int longstring = inputArray[0].length();
int count = 0;
vector<string> result;
for (int i = 0; i < length; i++)
{
if (longstring < inputArray[i].length())
{
longstring = inputArray[i].length();
}
count++;
}
for (int = 0; i<count;i++)
{
if (inputArray[i].length() != longstring)
{
inputArray[i].erase(inputArray.begin() + i);
count--;
i--;
}
}
return inputArray;
}
but i get this error no instance of overloaded fucntion "std::basic_string<_Elem,_Traits,_Alloc>::erase[with_Elem=char,_Traits=std::char_traits<char>,_Alloc=std::allocator<char>]" matches the argument list" in inputArray[i].erase(inputArray.begin()+i); this line
what's wrong?
There are other problems, but this specific compiler message is telling you that's not the right way to remove specific character(s) from a string.
However, reading the question in the OP, we see that you wanted to remove a string from a vector. To fix that one specific error, simply change
inputArray[i].erase( /*character position(s) in the string*/ )
to
inputArray.erase( /*some position in the array*/ )
Or you could fix it so it uses an iterator in the string denoted by inputArray[i] to actually delete characters from that string, which of course isn't what you said you wanted to do. The point is, the error message is because you're using the wrong iterator type because you think that you're working with a vector, but you actually told it to work with a string that you got out of the vector.
And then you will compile and have other issues which are well covered in comments already.
The issue with inputArray[i].erase(inputArray.begin() + i); can be fixed as shown in Kenny Ostrom's answer.
I'd like to point out that the OP could make use of the erase-remove idiom or even create a new vector with only the bigger strings instead (the posted code is already copying the source vector).
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
template <typename InputIt>
auto only_the_longest_of(InputIt first, InputIt last)
{
using value_type = typename std::iterator_traits<InputIt>::value_type;
std::vector<value_type> result;
// find the longest size
auto longest = std::max_element(first, last,
[](value_type const &a, value_type const &b) {
return a.size() < b.size();
});
if ( longest == last )
return result;
// extract only the longest ones, instead of erasing
std::copy_if( first, last, std::back_inserter(result)
, [max_size = longest->size()] (value_type const& v) {
return v.size() >= max_size;
});
return result;
}
template <typename T>
auto erase_the_shortest_from(std::vector<T> &input)
{
// find the longest size
auto longest = std::max_element(input.cbegin(), input.cend(),
[](T const &a, T const &b) {
return a.size() < b.size();
});
if ( longest == input.cend() || longest->size() == 0 )
return input.end();
// implement erase-remove idiom
return input.erase(std::remove_if(
input.begin(), input.end(), [max_size = longest->size()] (T const &v) {
return v.size() < max_size;
}));
}
int main()
{
std::vector<std::string> test = {
"aba", "aa", "ad", "vcd", "aba"
};
// The original vector remain unchanged
auto result = only_the_longest_of(test.cbegin(), test.cend());
for (auto const& str : result)
std::cout << str << '\n';
std::cout << '\n';
// This will change the vector
erase_the_shortest_from(test);
for (auto const& str : test)
std::cout << str << '\n';
}

Maps and substrings

I want to sort suffices of a string.
The most simple way to do that is putting all the suffices into map.
In order to use memory efficiently, I pass suffix as (str+i), where str is char* and i is a position suffix starts with. However, I found out that map is not going to sort these suffices. Here goes an example
typedef std::map < char*, int,Comparator> MapType;
MapType data;
// let's declare some initial values to this map
char* bob=(char* )"Bobs score";
char* marty=(char* ) "Martys score";
data.insert(pair<char*,int>(marty+1,15));
data.insert(pair<char*,int>(bob+1,10));
MapType::iterator end = data.end();
for (MapType::iterator it = data.begin(); it != end; ++it) {
std::cout << "Who(key = first): " << it->first;
std::cout << " Score(value = second): " << it->second << '\n';
}
The output is
Who(key = first): obs score Score(value = second): 10
Who(key = first): artys score Score(value = second): 15
However, strcmp, standard function for comparing strings, works correctly for bob+1 and marty+1. It says marty+1 is less than bob+1.
The map will sort by the address of the char*, not lexiographically. Change the key to a std::string or define a comparator.
EDIT:
It looks as though you have attempted to define a Comparator but the definition of it is not posted. Here is an example:
#include <iostream>
#include <map>
#include <string.h>
struct cstring_compare
{
bool operator()(const char* a_1, const char* a_2) const
{
return strcmp(a_1, a_2) < 0;
}
};
typedef std::map<const char*, int, cstring_compare> cstring_map;
int main()
{
cstring_map m;
m["bcd"] = 1;
m["acd"] = 1;
m["abc"] = 1;
for (cstring_map::iterator i = m.begin(); i != m.end(); i++)
{
std::cout << i->first << "\n";
}
return 0;
}
Output:
abc
acd
bcd
define a custom Comparator, eg
class compare_char {
public:
bool operator()(const char* lhs, const char* rhs) { return strcmp(lhs, rhs); }
};
define your map using this comparator instead of whatever you currently have. Alternatively, use a map with a key type that has a comparison operator that works with values, a std::string is better for you. Currently you have a map using char* as the key which compares char* types, ie. the value of the pointer, not the contents.
You should add the comparer class or function you are using since that is where your error is probably coming from.
There is a slight difference between strcmp and a map comparaison function.
strcmp returns 0 if a == b, -1 if a < b, 1 if a > b
comp returns true is a < b, false otherwise.
A correct way to implement the comparison function is the following:
bool operator() (char* lhs, char* rhs) const
{
return strcmp(lhs,rhs) < 0;
}

Vector point to another vector

What I have here is two arrays of different types that I'm converting to vectors.
int ham_array[] = {32,71,12,45,26};
char word_array[] = {"cat", "bat", "green", "red", "taxi"};
vector < int > hamvector (ham_array, ham_array + 5);
vector < char > wordvector(word_array, word_array + 5);
I am going to call a sort function to sort the elements of ham_array from least to greatest. At the same time, I would like the word_array to also get sorted the same way ham_vector gets sorted using references.
For example,
after I call sort(hamvector)
ham_array[] = {12, 26, 32, 45, 71}
and sort(wordvector)
word_array[] = {"green", "taxi", "cat", "red", "bat"};
Is there an easy way to do this?
Well for one thing, that would be char *word_array[], the way you declared it would be a string.
Anyway the way to do this is you declare a structure to keep these things paired:
struct t {string name; int number;};
vector<t> list;
// fill in list
// comparer to compare two such structs
bool comparer(t &a, t &b) { return a.number>=b.number; }
// and to sort the list
sort(list.begin(), list.end(), comparer);
If by simple, you mean a more direct way then yes. The std::sort() does support sorting of raw arrays as well:
sort(word_array, word_array + 5, wordcmp);
As Blindy showed, you need a comparator function to tell sort how the ordering is suppose to be done for your list of words. Otherwise you'll end up sorting by the memory address that the string resides at instead of by the letters in your string. Something like this should work:
int wordcmp(const char *lhs, const char *rhs)
{
return strncmp(lhs, rhs, 256) < 0;
}
One other note, in practice you'll want to prefer std::vector over just raw pointer arrays since the latter isn't as safe.
I've tried to find a solution to a similar problem before and ultimately had to sort it manually. Another way I imagine you could do this would be to write a sorter functor that can somehow figure out, based on which string is being sorted, which integer is associated, and sort based on that. This is terribly inefficient, so I would highly advise doing your own manual sorting using std::swap.
#include <map>
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
template<typename KeyType, typename ValueType>
class CMappedSorter
{
std::map<KeyType, ValueType>* const m_Mappings;
public:
CMappedSorter(std::map<KeyType, ValueType>* Mappings) : m_Mappings(Mappings)
{
}
bool operator()(KeyType& LHS, KeyType& RHS)
{
const ValueType LHSSortingValue = m_Mappings->find(LHS)->second;
const ValueType RHSSortingValue = m_Mappings->find(RHS)->second;
return (LHSSortingValue < RHSSortingValue);
}
};
int main(int argc, char* argv[])
{
std::vector<int> Integers;
std::vector<std::string> Strings;
Integers.push_back(3);
Integers.push_back(1);
Integers.push_back(2);
Strings.push_back("Apple");
Strings.push_back("Banana");
Strings.push_back("Cherry");
std::map<std::string, int> Mappings;
if(Integers.size() == Strings.size())
{
const unsigned int ElementCount = Strings.size();
// Generate mappings.
auto StringsIterator = Strings.begin();
auto IntegersIterator = Integers.begin();
for(unsigned int i = 0; i < ElementCount; ++i)
{
Mappings[*(StringsIterator)] = *(IntegersIterator);
++StringsIterator;
++IntegersIterator;
}
// Print out before sorting.
std::cout << "Before Sorting" << std::endl;
std::cout << "Int\tString" << std::endl;
StringsIterator = Strings.begin();
IntegersIterator = Integers.begin();
for(unsigned int i = 0; i < ElementCount; ++i)
{
std::cout << *(IntegersIterator) << '\t' << *(StringsIterator) << std::endl;
++StringsIterator;
++IntegersIterator;
}
// Sort
std::sort(Strings.begin(), Strings.end(), CMappedSorter<std::string, int>(&(Mappings)));
std::sort(Integers.begin(), Integers.end());
// Print out after sorting.
std::cout << "After Sorting" << std::endl;
std::cout << "Int\tString" << std::endl;
StringsIterator = Strings.begin();
IntegersIterator = Integers.begin();
for(unsigned int i = 0; i < ElementCount; ++i)
{
std::cout << *(IntegersIterator) << '\t' << *(StringsIterator) << std::endl;
++StringsIterator;
++IntegersIterator;
}
}
else
{
std::cout << "Error: Number of elements in each container are not equivalent." << std::endl;
}
}

Sorting a set<string> on the basis of length

My question is related to this.
I wanted to perform a sort() operation over the set with the help of a lambda expression as a predicate.
My code is
#include <set>
#include <string>
#include <iostream>
#include <algorithm>
int main() {
using namespace std;
string s = "abc";
set<string> results;
do {
for (int n = 1; n <= s.size(); ++n) {
results.insert(s.substr(0, n));
}
} while (next_permutation(s.begin(), s.end()));
sort (results.begin(),results.end());[](string a, string b)->bool{
size_t alength = a.length();
size_t blength = b.length();
return (alength < blength);
});
for (set<string>::const_iterator x = results.begin(); x != results.end(); ++x) {
cout << *x << '\n';
}
return 0;
}
But the numbers and types of errors were so complex that I couldn't understand how to fix them. Can someone tell me whats wrong with this code.
Edit: Note that Steve Townsend's solution is actually the one you're searching for, as he inlines as a C++0x Lambda what I write as C++03 code below.
Another solution would be to customize the std::set ordering function:
The std::set is already ordered...
The std::set has its own ordering, and you are not supposed to change it once it is constructed. So, the following code:
int main(int argc, char* argv[])
{
std::set<std::string> aSet ;
aSet.insert("aaaaa") ;
aSet.insert("bbbbb") ;
aSet.insert("ccccccc") ;
aSet.insert("ddddddd") ;
aSet.insert("e") ;
aSet.insert("f") ;
outputSet(aSet) ;
return 0 ;
}
will output the following result:
- aaaaa
- bbbbb
- ccccccc
- ddddddd
- e
- f
... But you can customize its ordering function
Now, if you want, you can customize your set by using your own comparison function:
struct MyStringLengthCompare
{
bool operator () (const std::string & p_lhs, const std::string & p_rhs)
{
const size_t lhsLength = p_lhs.length() ;
const size_t rhsLength = p_rhs.length() ;
if(lhsLength == rhsLength)
{
return (p_lhs < p_rhs) ; // when two strings have the same
// length, defaults to the normal
// string comparison
}
return (lhsLength < rhsLength) ; // compares with the length
}
} ;
In this comparison functor, I did handle the case "same length but different content means different strings", because I believe (perhaps wrongly) that the behaviour in the original program is an error. To have the behaviour coded in the original program, please remove the if block from the code.
And now, you construct the set:
int main(int argc, char* argv[])
{
std::set<std::string, MyStringLengthCompare> aSet ;
aSet.insert("aaaaa") ;
aSet.insert("bbbbb") ;
aSet.insert("ccccccc") ;
aSet.insert("ddddddd") ;
aSet.insert("e") ;
aSet.insert("f") ;
outputSet(aSet) ;
return 0 ;
}
The set will now use the functor MyStringLengthCompare to order its items, and thus, this code will output:
- e
- f
- aaaaa
- bbbbb
- ccccccc
- ddddddd
But beware of the ordering mistake!
When you create your own ordering function, it must follow the following rule:
return true if (lhs < rhs) is true, return false otherwise
If for some reason your ordering function does not respect it, you'll have a broken set on your hands.
std::sort rearranges the elements of the sequence you give it. The arrangement of the sequence in the set is fixed, so the only iterator you can have is a const iterator.
You'll need to copy results into a vector or deque (or such) first.
vector sortable_results( results.begin(), results.end() );
You can customize the ordering of the elements in the set by providing a custom predicate to determine ordering of added elements relative to extant members. set is defined as
template <
class Key,
class Traits=less<Key>,
class Allocator=allocator<Key>
>
class set
where Traits is
The type that provides a function
object that can compare two element
values as sort keys to determine their
relative order in the set. This
argument is optional, and the binary
predicate less is the default
value.
There is background on how to use lambda expression as a template parameter here.
In your case this translates to:
auto comp = [](const string& a, const string& b) -> bool
{ return a.length() < b.length(); };
auto results = std::set <string, decltype(comp)> (comp);
Note that this will result in set elements with the same string length being treated as duplicates which is not what you want, as far as I can understand the desired outcome.
sort requires random access iterators which set doesn't provide (It is a bidirectional iterator). If you change the code to use vector it compiles fine.
You cannot sort a set. It's always ordered on keys (which are elements themselves).
To be more specific, std::sort requires random access iterators. The iterators provided by std::set are not random.
Since I wrote the original code you're using, perhaps I can expand on it... :)
struct cmp_by_length {
template<class T>
bool operator()(T const &a, T const &b) {
return a.length() < b.length() or (a.length() == b.length() and a < b);
}
};
This compares by length first, then by value. Modify the set definition:
set<string, cmp_by_length> results;
And you're good to go:
int main() {
using namespace std;
string s = "abc";
typedef set<string, cmp_by_length> Results; // convenience for below
Results results;
do {
for (int n = 1; n <= s.size(); ++n) {
results.insert(s.substr(0, n));
}
} while (next_permutation(s.begin(), s.end()));
// would need to add cmp_by_length below, if I hadn't changed to the typedef
// i.e. set<string, cmp_by_length>::const_iterator
// but, once you start using nested types on a template, a typedef is smart
for (Results::const_iterator x = results.begin(); x != results.end(); ++x) {
cout << *x << '\n';
}
// of course, I'd rather write... ;)
//for (auto const &x : results) {
// cout << x << '\n';
//}
return 0;
}
std::set is most useful to maintain a sorted and mutating list. It faster and smaller to use a vector when the set itself wont change much once it's been built.
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
int main() {
using namespace std;
string s = "abc";
vector<string> results;
do {
for (size_t n = 1; n <= s.size(); ++n) {
results.push_back(s.substr(0, n));
}
} while (next_permutation(s.begin(), s.end()));
//make it unique
sort( results.begin(), results.end() );
auto end_sorted = unique( results.begin(), results.end() );
results.erase( end_sorted, results.end() );
//sort by length
sort (results.begin(),results.end());
[](string lhs, string rhs)->bool
{ return lhs.length() < rhs.length(); } );
for ( const auto& result: results ) {
cout << result << '\n';
}
}
I used the classic, sort/unique/erase combo to make the results set unique.I also cleaned up your code to be a little bit more c++0x-y.