zoukankan      html  css  js  c++  java
  • 字符串单词翻转

    题目要求:将字符串以词为单位进行翻转。如:"a bc def gh ij kml"变成"kml ij gh def bc a"。时间复杂度O(n),空间复杂度O(1)。

    思路:先将整个字符串按字母进行翻转,然后再逐个单词翻转。

    代码如下:

    #include<iostream>
    using namespace std;

    void wordturn(char *src, int len){
       //按字母翻转
       for(int i =0; i < len/2; i++){
          char temp = src[i];
          src[i] = src[len-i-1];
          src[len-i-1] = temp;
       }
     
       //寻找空格,翻转单词的字母
       char *phead = src;
       char *ptail = src;
       while('\0' != *phead && '\0' != *ptail){
          if(*ptail == ' '){
             int word_len = ptail - phead;
             for(int j=0 ; j < word_len/2; j++){
                char temp = phead[j];
                phead[j] = phead[word_len-1-j];
                phead[word_len-1-j] = temp;
             } 
             phead = ptail +1;
          }
        ptail++;
       }
    }

    int main(){
       char src[] = "  a bc   def gh ij kml   ";
       char *psrc = src;
       int len = sizeof(src)/sizeof(char);
       cout << src << endl;
       wordturn(psrc,len-1);
       cout << src << endl;

      return 0;
    }

  • 相关阅读:
    (元)黄公望---富春山居图(中国十大传世名画之八) 高清图下载
    Bloom Filter 原理与应用
    开始我的 JNI 入门吧
    javaScript的使用
    hash定义
    POJ3169 Layout(差分约束系统)
    青蛙的约会
    POJ 3414 Pots ( BFS , 打印路径 )
    你真的理解Java的this和super吗?
    十款优秀的在线JavaScript工具介绍
  • 原文地址:https://www.cnblogs.com/guotao/p/2998800.html
Copyright © 2011-2022 走看看