top of page

Daily Coding Problem #5

Writer's picture: Mischievous_FaceMischievous_Face

// Given a word W and a string S, find all starting indices in S which are anagrams of W.

// For example, given that W is "ab", and S is "abxaba", return 0, 3, and 4.


#include <vector>

#include <iostream>

#include <fstream>

#include <string>

#include <algorithm>

#include <sstream>

#include <thread>

#include <map>

#include <vector>

#include <string>


using namespace std;


vector<int> getAnagrams(string str1, string str2)

{

vector<int> indexList = vector<int>();

unsigned iterations = str2.size() - str1.size() + 1;

for (unsigned i = 0; i < iterations; ++i)

{

string subStr = str2.substr(i, str1.size());

unsigned total = str1.size();


for (unsigned j = 0; j < str1.size(); ++j)

{

size_t index = subStr.find(str1[j]);


if (index != string::npos)

{

subStr.replace(index, 1, "");

total--;

}

}


if (total == 0)

{

indexList.push_back(i);

}

}


return indexList;

}



int main(int argc, char** argv)

{

auto result = getAnagrams("ab", "abxaba");


cout << endl;

for (int i = 0; i < result.size(); ++i)

{

cout << result[i] << ",";

}


return 0;

}

37 views0 comments

Recent Posts

See All

Comments


© 2020 Josh Painter

bottom of page