剑指offer替换空格

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Solution {
public:
    string replaceSpace(string str) {
        stack<int> Mystack;
    int length=str.length();
    int blankCount=0;
    for(int i=0;i<length;i++)
    {
        if(str[i]==' ')
        {
            Mystack.push(i);
            blankCount++;
        }
    }
    int newLength=length+blankCount*2;
    string newstr(newLength,'0');
  
    int blankIndex=0;
    int i=length-1;
    int j=newLength-1;
    while(!Mystack.empty())
    {
        blankIndex=Mystack.top();
        Mystack.pop();
        while(i>blankIndex)
        {
            newstr[j]=str[i];
            j--;
            i--;
        }
        newstr[j--]='0';
        newstr[j--]='2';
        newstr[j--]=(char)(37);
        i--;
    }
    while(i>=0)
    {
        newstr[j]=str[i];
        j--;
        i--;
    }
    return newstr;
    }
};
原文地址:https://www.cnblogs.com/zhxshseu/p/5285168.html