分享

程序员面试攻略 5.5面试例题:颠倒单词的出现顺序

 shaobin0604@163.com 2006-10-22
5.5 面试例题:颠倒单词的出现顺序
请编写一个函数来颠倒单词在字符串里的出现顺序。假设所有单词都以空格为分隔符,标点符号也当作字母来对待。
比如:
input:       "Do or do not, there is no try."
output:      "try. no is there not, do or Do"

--------------------------- ReverseWords1.c --------------------------------------

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int reverseWords(char str[]) {
 char *buffer;
 int tokenReadPos, wordReadPos, wordEnd, writePos = 0;
 // Position of the last character is length - 1
 tokenReadPos = strlen(str) - 1;
 buffer = (char*) malloc(tokenReadPos + 2);
 if (!buffer)
  return 0; //reverseWords failed
 while (tokenReadPos >= 0) {
  if (str[tokenReadPos] == ‘ ‘) { //non-word characters, just write it
   buffer[writePos++] = str[tokenReadPos--];
  } else { //word character
   //store position of end of word
   wordEnd = tokenReadPos;  
   
   //scan to next non-word character
   while (tokenReadPos >= 0 && str[tokenReadPos] != ‘ ‘)
    tokenReadPos--;
   
   //tokenReadPos went past the start of the word
   wordReadPos = tokenReadPos + 1;

   //copy the characters of the word
   while (wordReadPos <= wordEnd) {
    buffer[writePos++] = str[wordReadPos++];
   }
  }
  
 }
 //NULL terminate buffer and copy over str
 buffer[writePos] = ‘\0‘;
 strcpy(str, buffer);

 free(buffer);
 
 //reverseWords successful
 return 1;
}

int main() {
 char str[] = "Do or do not, there is no try.";
 reverseWords(str);
 int i;
 for (i = 0; str[i] != ‘\0‘; i++) {
  printf("%c", str[i]);
 }
 printf("%c", ‘\n‘);
 return 0;
}
--------------------------- ReverseWords2.c --------------------------------------
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void reverseString(char str[], int start, int end) {
 char temp;
 while (start < end) {
  // swap character
  temp = str[start];
  str[start] = str[end];
  str[end] = temp;
  
  //move index towards middle
  start++;
  end--;
 }
}
void reverseWords(char str[]) {
 int start = 0, end = 0, length;
 
 length = strlen(str);
 
 //reverse entire string
 reverseString(str, 0, length - 1);
 
 while (end < length) {
  //skip non-word characters
  if (str[end] != ‘ ‘) {
   //save position of beginning of word
   start = end;
   
   //scan to next non-word character
   while (end < length && str[end] != ‘ ‘) {
    end++;
   }
   //back up to end of word
   end--;
   
   //reverse word
   reverseString(str, start, end);
  }
  //advanced to next token
  end++;
 }
}
int main() {
 char str[] = "Do or do not, there is no try.";
 reverseWords(str);
 int i;
 for (i = 0; str[i] != ‘\0‘; i++) {
  printf("%c", str[i]);
 }
 printf("%c", ‘\n‘);
 return 0; 
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多