LeetCode 面试题05. 替换空格

题目链接:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/

请实现一个函数,把字符串 s 中的每个空格替换成"%20"。

示例 1:

输入:s = "We are happy."

输出:"We%20are%20happy."

限制:

0 <= s 的长度 <= 10000

 1 char* replaceSpace(char* s){
 2     int len=strlen(s);
 3     int i,j=0,cnt=0;
 4     for(i=0;i<len;i++){
 5         if(s[i]==' ') cnt++;
 6     }
 7     char *ns=(char *)malloc(sizeof(char)*(len+3*(cnt+1)));
 8     for(i=0;i<len;i++){
 9         if(s[i]!=' '){
10             ns[j++]=s[i];
11         }else{
12             ns[j++]='%';
13             ns[j++]='2';
14             ns[j++]='0';
15         }
16     }
17     ns[j]='\0';
18     return ns;
19 }

猜你喜欢

转载自www.cnblogs.com/shixinzei/p/12405626.html