Merge pull request #1107 from hs-zhangsan/master

添加 541.反转字符串II C语言版本
This commit is contained in:
程序员Carl
2022-03-12 13:48:28 +08:00
committed by GitHub
2 changed files with 54 additions and 0 deletions

View File

@ -98,8 +98,31 @@ public:
## 其他语言版本
C
```c
char * reverseStr(char * s, int k){
int len = strlen(s);
for (int i = 0; i < len; i += (2 * k)) {
//判断剩余字符是否少于 k
k = i + k > len ? len - i : k;
int left = i;
int right = i + k - 1;
while (left < right) {
char temp = s[left];
s[left++] = s[right];
s[right--] = temp;
}
}
return s;
}
```
Java
```Java
//解法一
class Solution {

View File

@ -121,6 +121,37 @@ for (int i = 0; i < a.size(); i++) {
## 其他语言版本
C
```C
char* replaceSpace(char* s){
//统计空格数量
int count = 0;
int len = strlen(s);
for (int i = 0; i < len; i++) {
if (s[i] == ' ') {
count++;
}
}
//为新数组分配空间
int newLen = len + count * 2;
char* result = malloc(sizeof(char) * newLen + 1);
//填充新数组并替换空格
for (int i = len - 1, j = newLen - 1; i >= 0; i--, j--) {
if (s[i] != ' ') {
result[j] = s[i];
} else {
result[j--] = '0';
result[j--] = '2';
result[j] = '%';
}
}
result[newLen] = '\0';
return result;
}
```
Java
```Java