题目描述:
给定一组URL组件,请编写代码将这些组件拼接成一个完整的URL。
示例:
输入:
protocol = "http"
host = "leetcode.com"
path = "/path"
query = "query=123"
fragment = "fragment"
输出:
"http://leetcode.com/path?query=123#fragment"
解决方案:
Java 实现:
public class Solution {
public String buildUrl(String protocol, String host, String path, String query, String fragment) {
StringBuilder url = new StringBuilder();
url.append(protocol).append("://").append(host);
if (path != null) {
url.append('/').append(path.startsWith("/") ? path.substring(1) : path);
}
if (query != null) {
url.append('?').append(query);
}
if (fragment != null) {
url.append('#').append(fragment);
}
return url.toString();
}
}
Python 实现:
class Solution:
def buildUrl(self, protocol, host, path, query, fragment):
url = protocol + "://" + host
if path:
url += '/' + path.lstrip('/')
if query:
url += '?' + query
if fragment:
url += '#' + fragment
return url
C++ 实现:
#include <iostream>
#include <string>
std::string buildUrl(std::string protocol, std::string host, std::string path, std::string query, std::string fragment) {
std::string url = protocol + "://" + host;
if (!path.empty()) {
url += '/' + path.substr(path.starts_with('/') ? 1 : 0);
}
if (!query.empty()) {
url += '?' + query;
}
if (!fragment.empty()) {
url += '#' + fragment;
}
return url;
}
int main() {
std::string protocol = "http";
std::string host = "leetcode.com";
std::string path = "/path";
std::string query = "query=123";
std::string fragment = "fragment";
std::cout << buildUrl(protocol, host, path, query, fragment) << std::endl;
return 0;
}
JavaScript 实现:
function buildUrl(protocol, host, path, query, fragment) {
let url = protocol + "://" + host;
if (path) {
url += '/' + path.replace(/^\//, '');
}
if (query) {
url += '?' + query;
}
if (fragment) {
url += '#' + fragment;
}
return url;
}
// 测试示例
console.log(buildUrl("http", "leetcode.com", "/path", "query=123", "fr