码迷,mamicode.com
首页 > 其他好文 > 详细

剑指offer替换空格

时间:2016-03-16 22:41:36      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }
};

剑指offer替换空格

标签:

原文地址:http://www.cnblogs.com/zhxshseu/p/5285168.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!