推 yauhh:原來如此,做得好 10/16 15:07
: 若我沒有弄錯,這個解法還是需要用到stack,只是pop與push的規則很單純
按照前面 manlike 大提供方法,寫了一個沒用到 stack 版本,
不確定有沒有寫對,看看吧
※ 其中的 isValid() 函數,因為我不知道轉換規格,所以不是正確的
程式碼線上版:http://codepad.org/0yhjKaFf
#include <iostream>
#include <string>
using namespace std;
char toASCII(char c1, char c2) {
int tmp = 16 * (c1-'0') + (c2-'0');
return (char)tmp; // mov al, byte ptr[tmp]
}
bool isValid(char c1, char c2) {
if (c1 == '%' || c2 == '%')
return false;
else
return true;
}
string deURL(const string &encURL) {
string decURL = encURL;
size_t index = encURL.size();
while (index >= 2) {
while (decURL[index-2] == '%') {
char c1 = decURL[index-1], c2 = decURL[index];
if (isValid(c1, c2) == false) break;
char ch = toASCII(c1, c2);
if (ch == '%') {
decURL[index-1] = 0;
string tmp = decURL.c_str();
const char *suffixStr = decURL.c_str() + index + 1;
if (suffixStr[0] != 0) {
tmp.append(suffixStr);
if (suffixStr[1] == 0) {
index--;
}
} else {
index = index - 2;
}
decURL = tmp;
cout << decURL << "\n";
} else {
decURL[index-2] = ch;
decURL[index-1] = 0;
string tmp = decURL.c_str();
const char *suffixStr = decURL.c_str() + index + 1;
if (suffixStr[0] != 0) {
tmp.append(suffixStr);
}
decURL = tmp;
cout << decURL << "\n";
}
}
index--;
}
return decURL;
}
int main() {
const string encodedURL = "http:://www.xxx.com/arg?C=0x%25%34%31B%25%25%25";
cout << encodedURL.size() << ", " << encodedURL << "\n";
string decodedURL = deURL(encodedURL);
cout << "decode result = "<< decodedURL << "\n";
return 0;
}
執行結果:
--------------------------------------
47, http:://www.xxx.com/arg?C=0x%25%34%31B%25%25%25
http:://www.xxx.com/arg?C=0x%25%34%31B%25%25%
http:://www.xxx.com/arg?C=0x%25%34%31B%25%%
http:://www.xxx.com/arg?C=0x%25%34%31B%%%
http:://www.xxx.com/arg?C=0x%25%341B%%%
http:://www.xxx.com/arg?C=0x%2541B%%%
http:://www.xxx.com/arg?C=0x%41B%%%
http:://www.xxx.com/arg?C=0xAB%%%
decode result = http:://www.xxx.com/arg?C=0xAB%%%
--------------------------------------
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 124.8.146.188