Created
March 9, 2016 09:01
-
-
Save rickyzhang-cn/2d46f22de121d1c9dea0 to your computer and use it in GitHub Desktop.
interview solution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
#include <map> | |
#include <string> | |
#include <iostream> | |
#include <cctype> | |
using namespace std; | |
bool Substitude(const string &template_str, map<string,string> &mapping, string &output) { | |
int state=0; | |
string var; | |
for(auto &c:template_str) { | |
switch(c) { | |
case '$': | |
if(state == 0) { | |
state=1; | |
} else if(state == 1) { | |
if(var.empty()) { | |
output+=c; | |
state=0; | |
} else { | |
auto r=mapping.find(var); | |
if(r != mapping.end()) | |
output+=r->second; | |
else | |
return false; | |
state=1; | |
var.clear(); | |
} | |
} else { | |
var+=c; | |
} | |
break; | |
case '{': | |
if(state == 0) | |
output+=c; | |
else if(state == 1) | |
state=2; | |
else | |
var+=c; | |
break; | |
case '}': | |
if(state == 0) | |
output+=c; | |
else if(state == 1) | |
var+=c; | |
else { | |
auto r=mapping.find(var); | |
if(r != mapping.end()) | |
output+=r->second; | |
else | |
return false; | |
} | |
state=0; | |
var.clear(); | |
break; | |
default: | |
if(state == 0) | |
output+=c; | |
else if(state == 1) { | |
if(isalnum(c)) { | |
var+=c; | |
} else { | |
auto r=mapping.find(var); | |
if(r != mapping.end()) | |
output+=r->second; | |
else | |
return false; | |
output+=c; | |
state=0; | |
var.clear(); | |
} | |
} | |
else | |
var+=c; | |
} | |
} | |
if(state == 0) | |
return true; | |
else if(state == 1) { | |
auto r=mapping.find(var); | |
if(r != mapping.end()) | |
output+=r->second; | |
else | |
return false; | |
return true; | |
} | |
else | |
return false; | |
} | |
int main() { | |
string template_str("abc$$def$VAR1-${VAR2}def"); | |
map<string,string> mapping; | |
mapping.emplace(make_pair(string("VAR1"),string("ricky"))); | |
mapping.emplace(make_pair(string("VAR2"),string("zhang"))); | |
string output; | |
if(Substitude(template_str,mapping,output)) | |
cout<<"the result:"<<output<<endl; | |
else | |
cout<<"something goes wrong"<<endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment