
이 문제는 HEX -> DEC -> CHR 방식으로 변환을 해주어 풀 수 있다.
먼저, 주어진 문자열에 있는 Encoded String을 모두 추출하여 vector에 추가 해 두고
vector 안에 있는 값들을 변환하여 치환하는 방식으로 문제를 풀면 된다.
간단한 문제지만, 함정 하나 때문에 정답을 얻는데 좀 오래 걸렸다.
C++에는 일치하는 모든 문자열을 치환하는 함수가 없어서 직접 작성하였는데
이 부분이 오류였다. 모든 문자열이 아니라 한번만 치환해야 했던것 !
예를들어 abc%2525%2525abc 를 넣어주면
abc%25%25abc 이렇게 출력해야하는데
%25, %25 두개를 vector에 넣어두고 루프를 실행하면
첫번째 루프: abc%25%25abc
두번째 루프: abc%%abc 이런식으로 되서 오답처리 되었던 것.
알고리즘 문제 풀땐 질문을 잘 이해하는것이 매우 중요한것 같다.
날 함정에 빠뜨렸던 replace 함수는 주석처리되어있다.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/* 문자열 치환
void replace(string &str_text, string str1, string str2){
int pos = 0;
while((pos=str_text.find(str1, pos))!=string::npos){
str_text.erase(pos, str1.length());
str_text.insert(pos, str2);
pos += str2.length();
}
}
*/
int hex_to_dec(char c){
/*
* 48~57: 0~9
* 65~90: A~Z
* 97~122: a~z
*/
int dec = 0;
if(c<58)
dec = c - '0';
else if(c<90)
dec = c - 55;
else if(c<122)
dec = c - 87;
else
return -1;
return dec;
}
char hex_to_char(string hex){
return hex_to_dec(hex.at(0)) * 16 + hex_to_dec(hex.at(1));
}
class URI{
public:
URI(void);
URI(string uri);
string uri;
string decode();
};
URI::URI(){
uri = "";
}
URI::URI(string uri){
this->uri = uri;
}
string URI::decode(){
vector<string> v;
string decoded = uri;
int pos=0;
while((pos=uri.find("%", pos))!=string::npos){
v.push_back(uri.substr(pos, 3));
pos += 3;
}
pos=0;
for(string s : v){
// replace(decoded, s, string(1, hex_to_char(s.substr(1,2)))) ;
pos=decoded.find(s,pos);
decoded.erase(pos,3);
decoded.insert(pos++, string(1, hex_to_char(s.substr(1,2))));
}
return decoded;
}
int main(){
int t = 0;
cin >> t;
vector<URI> v;
for(int i=0; i<t; i++){
string input;
cin >> input;
URI uri(input);
v.push_back(uri);
}
for(URI uri : v){
cout << uri.decode() << endl;
}
}
