Problem
/*
* ##Pretty much interested question asked in AMAZON Written test##
Take a string, store it as digits; str="678876". Now Check if the given str return TWO EQUAL PARTS with equal sum (6+7+8=8+7+6);if it is correct then replace the str(678876) in the new string, str1="12345876678"
Final output should be: "12345678876"
I tried this ..but the interviewer didnt satisfy..
*
*/
Solution
/*
============================================================================
Author : James Chen
Email : a.james.chen@gmail.com
Description : Change string
Created Date : 20-September-2013
Last Modified :
============================================================================
*/
#include <iostream>
#include <iomanip>
#include <vector>
#include <limits>
#include <unordered_map>
#include <string>
using namespace std;
string ChangeString(string str){
unordered_map<int, int> maps;
int sum = 0;
for(int i = 0; i < str.size(); ++ i){
sum += str[i];
maps[sum] = i;
}
if(sum % 2 != 0 ||
maps.find(sum / 2) == maps.end()){
cout << "Cannot find TWO EQUAL PARTS";
return "";
}
return "12345" + str.substr(maps[sum / 2] + 1, str.size() - maps[sum / 2])
+ str.substr(0, maps[sum / 2] + 1);
}
void DoTest(string str)
{
cout << "The test string : " << str << endl;
cout << "Output : " << ChangeString(str) << endl;
}
int main(int argc, char* argv[])
{
DoTest("678876");
DoTest("67876");
return 0;
}
Output
The test string : 678876
Output : 12345876678
The test string : 67876
Cannot find TWO EQUAL PARTSOutput :
Press any key to continue . . .