카타 7급 Reverse words

1 C[ | ]

#include <stdlib.h>
char* reverseWords(const char* text)
{  
  int n, i, j;  
  for(i=0; *(text+i); i++,n++); 
  char* s = (char*)malloc((n+1)*sizeof(char));
  char* ps = s; 
  for(i=1; *text!=0; i++, *(text++)) {
    if(*text==' ') {
      for(j=1; j<i; j++)  *(s++) = text[-j];
      *(s++) = ' '; 
      i = 0;
    }   
  }
  for(j=1; j<=i; j++) *(s++) = text[-j]; 
  *(s-1) = 0;
  return(ps);
}
#include <stdlib.h>
void reverse(char* begin, char* end) {
  char temp;
  while( begin < end ) {
    temp = *begin;
    *begin++ = *end;
    *end-- = temp;
  }
}
char* reverseWords(const char* text) {
  char *str = malloc(strlen(text)+1);
  strcpy(str, text);
  char* begin;
  char* pos;
  for(begin=pos=str; *pos; pos++) {
    if( *pos == ' ') {
      reverse(begin, pos-1); 
      begin = pos + 1;
    }
  }
  reverse(begin, pos-1); 
  return str;
}

2 C++[ | ]

std::string reverse_words(std::string str)
{
  string res;
  string word;
  for(char c : str) {
    if(c == ' ') {
      res += word + c;
      word = "";
      continue;
    }
    word = c + word;
  }
  res += word;
  return res;
}
std::string reverse_words(std::string str)
{
  auto i { begin(str) };
  auto j { i };
  for (; i !=end(str); i++) {
    if ( *i == ' ' ) {
      reverse(j, i);
      j = i + 1;
    }
  }
  reverse(j, i);
  return str;
}
vector<string> explode(char delim, string const & s) {
   vector<string> tokens;
   istringstream tokenStream(s);
   for(string token; getline(tokenStream, token, delim); ) tokens.push_back(token);
   if(s.back()==delim) tokens.push_back("");
   return tokens;
}
string implode( const string &glue, const vector<string> &pieces ) {
    string res;
    int len = pieces.size();
    for(int i=0; i<len; i++) {
        res += pieces[i];
        if( i < len-1 ) res += glue;
    }
    return res;
}
std::string reverse_words(std::string str)
{
  vector<string> words = explode(' ', str);
  for(int i=0; i<words.size(); i++) {
    reverse(words[i].begin(), words[i].end());
  }
  string res = implode(" ", words);
  return res;
}
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}