华为OD机试 - 字符串拼接(Java & JS & Python & C & C++)
题目描述:
给定两个字符串s1和s2,请编写程序,其功能是把s2串插入到s1串的字符之间。
解题思路:
- 确定s1和s2的长度。
- 创建一个新的字符串,长度为s1长度加两倍s2长度减一。
- 遍历s1的每个字符,每遍历一个字符就插入s2。
- 如果s1有剩余字符,则插入剩下的s2字符。
Java 示例代码:
public class Main {
public static void main(String[] args) {
String s1 = "abcd";
String s2 = "12";
System.out.println(insertString(s1, s2));
}
public static String insertString(String s1, String s2) {
int s1Len = s1.length();
int s2Len = s2.length();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s1Len; i++) {
sb.append(s1.charAt(i));
if (i < s1Len - 1) {
sb.append(s2);
}
}
if (s1Len * s2Len > s1Len) {
sb.append(s2.substring(0, s2Len - 1));
}
return sb.toString();
}
}
JavaScript 示例代码:
function insertString(s1, s2) {
let result = '';
for (let i = 0; i < s1.length; i++) {
result += s1[i];
if (i < s1.length - 1) {
result += s2;
}
}
if (s1.length * s2.length > s1.length) {
result += s2.substring(0, s2.length - 1);
}
return result;
}
console.log(insertString("abcd", "12"));
Python 示例代码:
def insert_string(s1, s2):
result = ''
for i in range(len(s1)):
result += s1[i]
if i < len(s1) - 1:
result += s2
if len(s1) * len(s2) > len(s1):
result += s2[:len(s2) - 1]
return result
print(insert_string("abcd", "12"))
C 示例代码:
#include <stdio.h>
#include <string.h>
char* insertString(char* s1, char* s2) {
int s1Len = strlen(s1);
int s2Len = strlen(s2);
char* result = (char*)malloc(sizeof(char) * (s1Len + s2Len));
int i, j;
for (i = j = 0; i < s1Len; i++) {
result[j++] = s1[i];
if (i < s1Len - 1) {
strcpy(result + j, s2);
j += s2Len;
}
}
if (s1Len * s2Len > s1Len) {
strncpy(result + j, s2, s2Len - 1);
result[j + s2Len - 1] = '\0';
}
return result;
}
int main() {
char s1[] = "abcd";
char s2[] = "12";
char* result = insertString(s1, s2);
printf("%s\n", result);
free(result);
return 0;
}
C++ 示例代码:
#include <iostream>
#include <string>
std::string insertString(std::string s1, std::string s2)
评论已关闭