Reverse the ordering of words in a string

后端 未结 30 3789
青春惊慌失措
青春惊慌失措 2020-11-22 10:23

I have this string s1 = \"My name is X Y Z\" and I want to reverse the order of the words so that s1 = \"Z Y X is name My\".

I can do it u

30条回答
  •  抹茶落季
    2020-11-22 10:57

    You cannot do the reversal without at least some extra data structure. I think the smallest structure would be a single character as a buffer while you swap letters. It can still be considered "in place", but it's not completely "extra data structure free".

    Below is code implementing what Bill the Lizard describes:

    string words = "this is a test";
    
    // Reverse the entire string
    for(int i = 0; i < strlen(words) / 2; ++i) {
      char temp = words[i];
      words[i] = words[strlen(words) - i];
      words[strlen(words) - i] = temp;
    }
    
    // Reverse each word
    for(int i = 0; i < strlen(words); ++i) {
      int wordstart = -1;
      int wordend = -1;
      if(words[i] != ' ') {
        wordstart = i;
        for(int j = wordstart; j < strlen(words); ++j) {
          if(words[j] == ' ') {
            wordend = j - 1;
            break;
          }
        }
        if(wordend == -1)
          wordend = strlen(words);
        for(int j = wordstart ; j <= (wordend + wordstart) / 2 ; ++j) {
          char temp = words[j];
          words[j] = words[wordend - (j - wordstart)];
          words[wordend - (j - wordstart)] = temp;
        }
        i = wordend;
      }
    }
    

提交回复
热议问题