# C++ Solution Using String Vector

• I stored long urls in a vector, and use their vector index to compute the short url. With A-Z, a-z, 0-9, we could represent 62 in one character.

``````class Solution {
public:
vector<string> urlList;
int listSize = 0;
// Encodes a URL to a shortened URL.
string encode(string longUrl) {
urlList.push_back(longUrl);
listSize += 1;
return pos2url(listSize-1);
}

// Decodes a shortened URL to its original URL.
string decode(string shortUrl) {
int pos = url2pos(shortUrl);
return urlList[pos];
}

string pos2url(long pos){
string url;
while (pos > 0){
long cur = pos % 62;
if (cur < 9){
url += ('0' + cur);
}else if (cur < 26){
url += ('a' + (cur-10));
}else{
url += ('A' + (cur-36));
}
pos /= 62;
}
return url;
}

int url2pos(string url){
int pos = 0;
for (int i = 0; i < url.size(); i++){
pos *= 62;
if (url[i] >= '0' && url[i] <= '9'){
pos += (url[i] - '0');
}else if (url[i] >= 'a' && url[i] <= 'z'){
pos += (url[i] - 'a' + 10);
}else{
pos += (url[i] - 'a' + 36);
}
}
return pos;
}
};

// Your Solution object will be instantiated and called as such:
// Solution solution;
// solution.decode(solution.encode(url));
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.