LeetCode face questions 05. Replace spaces

Topic links: https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/

Please implement a function, replace each space in the string s to "20%."

Example 1:

输入:s = "We are happy."

Output: "We% 20are% 20happy."

limit:

Length 0 <= s of <= 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 }

 

Guess you like

Origin www.cnblogs.com/shixinzei/p/12405626.html