zoukankan      html  css  js  c++  java
  • 去掉字符串中多余的空格【微软面试提】

    题目:

    1、 remove掉给定字符串中的多余空格,要求达到以下要求
    A 无连续相邻的两个空格
    B 字符串开头和结尾无空格
    C 新的一行开头和结尾无空格
      
    要得到满分,必须满足以下两个条件
    A 不能增加新的内存空间
    B只能循环字符串一次
    C不准用其他库函数

    思路:循环过程中记录每个字符需要往前移动的距离,每个字符按照求出的距离向前移动(整个过程只需要遍历一次字符串数组)

    我的实现代码如下:

    /*This is the template of *.cpp files */
    #include<iostream>
    using namespace std;

    void clear_space(char *p){
        int jump = 0;
        int i = 0;
        int temp = 0;
        while(p[i] == ' ' && p[i] != ''){
            ++jump;
            ++i;
        }
        while(p[i] != ''){
            if(p[i] != ' '){
                p[i - jump] = p[i];
                temp = 0;
            }else{
                ++temp;
                if(temp > 1)
                    ++jump;
                else
                    p[i - jump] = p[i];
            }
            ++i;
        }
        if(p[i - 1] == ' '){
            p[i - jump - 1] = ' ';
        }
        p[i - jump] = '';
    }

    int main(){
        char q[] = "    kjf     dshgjk  sjdhfdj asdf   sdf  dsf ";
        int i = 0;
        cout<<q<<endl;
        clear_space(q);
        cout<<q<<endl;
        return 0;
    }

  • 相关阅读:
    使用cocoapods出现问题fetch of the ‘master’ 的解决方法
    说说ASP.NET的表单验证
    php分页类
    php校验
    mySQL时间
    asp .NET弹出窗口 汇总(精华,麒麟创想)
    (转)MVC 3 数据验证 Model Validation 详解
    (转)linux性能优化总结
    (转)ASP.NET缓存全解析6:数据库缓存依赖
    SQL Server是如何让定时作业
  • 原文地址:https://www.cnblogs.com/candycloud/p/3595777.html
Copyright © 2011-2022 走看看