Invertire in modo efficiente l'ordine delle parole (non dei caratteri) in una matrice di caratteri

StackOverflow https://stackoverflow.com/questions/47402

Domanda

Dato un array di caratteri che forma una frase di parole, fornire un algoritmo efficiente per invertire l'ordine delle parole (non dei caratteri) al suo interno.

Esempio di input e output:

>>> reverse_words("this is a string")
'string a is this'

Dovrebbe essere O(N) tempo e O(1) spazio (split() e non sono consentiti l'inserimento o l'estrazione dallo stack).

Il puzzle è tratto da Qui.

È stato utile?

Soluzione

Una soluzione in C/C++:

void swap(char* str, int i, int j){
    char t = str[i];
    str[i] = str[j];
    str[j] = t;
}

void reverse_string(char* str, int length){
    for(int i=0; i<length/2; i++){
        swap(str, i, length-i-1);
    }
}
void reverse_words(char* str){
    int l = strlen(str);
    //Reverse string
    reverse_string(str,strlen(str));
    int p=0;
    //Find word boundaries and reverse word by word
    for(int i=0; i<l; i++){
        if(str[i] == ' '){
            reverse_string(&str[p], i-p);
            p=i+1;
        }
    }
    //Finally reverse the last word.
    reverse_string(&str[p], l-p);
}

Questo dovrebbe essere O(n) nel tempo e O(1) nello spazio.

Modificare:Pulito un po'.

Il primo passaggio sulla stringa è ovviamente O(n/2) = O(n).Il secondo passaggio è O(n + lunghezza combinata di tutte le parole / 2) = O(n + n/2) = O(n), il che rende questo algoritmo O(n).

Altri suggerimenti

spingere una stringa su uno stack e poi estrarla: è ancora O(1)?essenzialmente, è come usare split()...

O(1) non significa sul posto?Questo compito diventa semplice se possiamo semplicemente aggiungere stringhe e cose del genere, ma ciò utilizza spazio...

MODIFICARE:Thomas Watnedal ha ragione.Il seguente algoritmo è O(n) nel tempo e O(1) nello spazio:

  1. stringa inversa sul posto (prima iterazione sulla stringa)
  2. invertire ogni parola (invertita) sul posto (altre due iterazioni sulla stringa)
    1. trova il confine della prima parola
    2. invertire all'interno di questo confine di parola
    3. ripetere per la parola successiva fino al termine

Immagino che dovremmo dimostrare che il passaggio 2 è in realtà solo O(2n)...

#include <string>
#include <boost/next_prior.hpp>

void reverse(std::string& foo) {
    using namespace std;
    std::reverse(foo.begin(), foo.end());
    string::iterator begin = foo.begin();
    while (1) {
        string::iterator space = find(begin, foo.end(), ' ');
        std::reverse(begin, space);
        begin = boost::next(space);
        if (space == foo.end())
            break;
    }
}

Ecco la mia risposta.Nessuna chiamata alla libreria e nessuna struttura dati temporanea.

#include <stdio.h>

void reverse(char* string, int length){
    int i;
    for (i = 0; i < length/2; i++){
        string[length - 1 - i] ^= string[i] ;
        string[i] ^= string[length - 1 - i];
        string[length - 1 - i] ^= string[i];
    }   
}

int main () {
char string[] = "This is a test string";
char *ptr;
int i = 0;
int word = 0;
ptr = (char *)&string;
printf("%s\n", string);
int length=0;
while (*ptr++){
    ++length;
}
reverse(string, length);
printf("%s\n", string);

for (i=0;i<length;i++){
    if(string[i] == ' '){
       reverse(&string[word], i-word);
       word = i+1;
       }
}   
reverse(&string[word], i-word); //for last word             
printf("\n%s\n", string);
return 0;
}

In pseudo codice:

reverse input string
reverse each word (you will need to find word boundaries)

@Daren Thomas

Implementazione del tuo algoritmo (O(N) nel tempo, O(1) nello spazio) in D (Marte digitale):

#!/usr/bin/dmd -run
/**
 * to compile & run:
 * $ dmd -run reverse_words.d
 * to optimize:
 * $ dmd -O -inline -release reverse_words.d
 */
import std.algorithm: reverse;
import std.stdio: writeln;
import std.string: find;

void reverse_words(char[] str) {
  // reverse whole string
  reverse(str);

  // reverse each word
  for (auto i = 0; (i = find(str, " ")) != -1; str = str[i + 1..length])
    reverse(str[0..i]);

  // reverse last word
  reverse(str);
}

void main() {
  char[] str = cast(char[])("this is a string");
  writeln(str);
  reverse_words(str);
  writeln(str);
}

Produzione:

this is a string
string a is this

in Rubino

"questa è una stringa".split.reverse.join(" ")

In C:(C99)

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

void reverseString(char* string, int length)
{
    char swap;
    for (int i = 0; i < length/2; i++)
    {
        swap = string[length - 1 - i];
        string[length - 1 - i] = string[i];
        string[i] = swap;
    }   
}

int main (int argc, const char * argv[]) {
    char teststring[] = "Given an array of characters which form a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it.";
    printf("%s\n", teststring);
    int length = strlen(teststring);
    reverseString(teststring, length);
    int i = 0;
    while (i < length)
    {
        int wordlength = strspn(teststring + i, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
        reverseString(teststring + i, wordlength);
        i += wordlength + 1;
    }
    printf("%s\n", teststring);
    return 0;
}

Questo dà l'output:

Dato una serie di personaggi che formano una frase di parole, dare un algoritmo efficiente per invertire l'ordine delle parole (non caratteri) in esso.

.It in) caratteri non (parole dell'ordine del contrario all'algoritmo efficiente e un dare, parole di frase una forma che caratteri di array un dato

Ciò richiede al massimo 4N di tempo, con uno spazio piccolo e costante.Sfortunatamente, non gestisce la punteggiatura o le maiuscole con garbo.

O(N) nello spazio e O(N) nel tempo soluzione in Python:

def reverse_words_nosplit(str_):
  """
  >>> f = reverse_words_nosplit
  >>> f("this is a string")
  'string a is this'
  """
  iend = len(str_)
  s = ""
  while True:
    ispace = str_.rfind(" ", 0, iend)
    if ispace == -1:
      s += str_[:iend]
      break
    s += str_[ispace+1:iend]
    s += " "
    iend = ispace
  return s

Dovresti utilizzare quella che è nota come funzione ricorsiva iterativa, che è O(N) nel tempo poiché richiede N (N è il numero di parole) iterazioni per essere completata e O(1) nello spazio poiché ciascuna iterazione mantiene il proprio stato all'interno gli argomenti della funzione.

(define (reverse sentence-to-reverse)
  (reverse-iter (sentence-to-reverse ""))

(define (reverse-iter(sentence, reverse-sentence)
  (if (= 0 string-length sentence)
    reverse-sentence
    ( reverse-iter( remove-first-word(sentence), add-first-word(sentence, reverse-sentence)))

Nota:L'ho scritto nello schema in cui sono un principiante assoluto, quindi mi scuso per la mancanza di una corretta manipolazione delle stringhe.

rimuovi-prima-parola trova il limite della prima parola della frase, quindi prende quella sezione di caratteri (inclusi spazio e punteggiatura) e la rimuove e restituisce una nuova frase

add-first-word trova il limite della prima parola della frase, quindi prende quella sezione di caratteri (inclusi spazio e punteggiatura) e la aggiunge alla frase inversa e restituisce il nuovo contenuto della frase inversa.

QUESTO PROGRAMMA CONSISTE PER INVERTIRE LA FRASE USANDO PUNTATORI IN "linguaggio C" Di Vasantha Kumar e Sundaramoorthy del KONGU ENGG COLLEGE, Erode.

NOTA:La frase deve terminare con punto(.)Perché il carattere null non viene assegnato automaticamente alla fine della frase*

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

int main()
{
char *p,*s="this is good.",*t;
int i,j,a,l,count=0;

l=strlen(s);

p=&s[l-1];

t=&s[-1];
while(*t)
   {
      if(*t==' ')
     count++;
     t++;
   }
   a=count;
  while(l!=0)
   {
for(i=0;*p!=' '&&t!=p;p--,i++);
   p++;

  for(;((*p)!='.')&&(*p!=' ');p++)
    printf("%c",*p);
  printf(" ");
  if(a==count)
   {
     p=p-i-1;
     l=l-i;
   }
  else
   {
     p=p-i-2;
     l=l-i-1;
   }

count--;
  }

return 0;  
}

Spingi ogni parola su una pila.Estrai tutte le parole dalla pila.

using System;

namespace q47407
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            string s = Console.ReadLine();
            string[] r = s.Split(' ');
            for(int i = r.Length-1 ; i >= 0; i--)
                Console.Write(r[i] + " ");
            Console.WriteLine();

        }
    }
}

modificare:credo che dovrei leggere tutta la domanda...proseguire.

Efficiente in termini di tempo:ci sono voluti meno di 2 minuti per scrivere in REBOL:

reverse_words: func [s [string!]] [form reverse parse s none]

Provalo:reverse_words "questa è una stringa" "stringa a è questa"

Una soluzione C++:

#include <string>
#include <iostream>
using namespace std;

string revwords(string in) {
    string rev;
    int wordlen = 0;
    for (int i = in.length(); i >= 0; --i) {
        if (i == 0 || iswspace(in[i-1])) {
            if (wordlen) {
                for (int j = i; wordlen--; )
                    rev.push_back(in[j++]);
                wordlen = 0;
            }
            if (i > 0)
                rev.push_back(in[i-1]);
        }
        else
            ++wordlen;
    }
    return rev;
}

int main() {
    cout << revwords("this is a sentence") << "." << endl;
    cout << revwords("  a sentence   with extra    spaces   ") << "." << endl;
    return 0;
}

Una soluzione Ruby.

# Reverse all words in string
def reverse_words(string)
  return string if string == ''

  reverse(string, 0, string.size - 1)

  bounds = next_word_bounds(string, 0)

  while bounds.all? { |b| b < string.size }
    reverse(string, bounds[:from], bounds[:to])
    bounds = next_word_bounds(string, bounds[:to] + 1)
  end

  string
end

# Reverse a single word between indices "from" and "to" in "string"
def reverse(s, from, to)
    half = (from - to) / 2 + 1

    half.times do |i|
        s[from], s[to] = s[to], s[from]
        from, to = from.next, to.next
    end

    s
end

# Find the boundaries of the next word starting at index "from"
def next_word_bounds(s, from)
  from = s.index(/\S/, from) || s.size
  to = s.index(/\s/, from + 1) || s.size

  return { from: from, to: to - 1 }
end

in C#, sul posto, O(n) e testato:

static char[] ReverseAllWords(char[] in_text)
{
    int lindex = 0;
    int rindex = in_text.Length - 1;
    if (rindex > 1)
    {
        //reverse complete phrase
        in_text = ReverseString(in_text, 0, rindex);

        //reverse each word in resultant reversed phrase
        for (rindex = 0; rindex <= in_text.Length; rindex++)
        {
            if (rindex == in_text.Length || in_text[rindex] == ' ')
            {
                in_text = ReverseString(in_text, lindex, rindex - 1);
                lindex = rindex + 1;
            }
        }
    }
    return in_text;
}

static char[] ReverseString(char[] intext, int lindex, int rindex)
{
    char tempc;
    while (lindex < rindex)
    {
        tempc = intext[lindex];
        intext[lindex++] = intext[rindex];
        intext[rindex--] = tempc;
    }
    return intext;
}

Questo problema può essere risolto con O(n) nel tempo e O(1) nello spazio.Il codice di esempio appare come indicato di seguito:

    public static string reverseWords(String s)
    {

        char[] stringChar = s.ToCharArray();
        int length = stringChar.Length, tempIndex = 0;

        Swap(stringChar, 0, length - 1);

        for (int i = 0; i < length; i++)
        {
            if (i == length-1)
            {
                Swap(stringChar, tempIndex, i);
                tempIndex = i + 1;
            }
            else if (stringChar[i] == ' ')
            {
                Swap(stringChar, tempIndex, i-1);
                tempIndex = i + 1;
            }
        }

        return new String(stringChar);
    }

    private static void Swap(char[] p, int startIndex, int endIndex)
    {
        while (startIndex < endIndex)
        {
            p[startIndex] ^= p[endIndex];
            p[endIndex] ^= p[startIndex];
            p[startIndex] ^= p[endIndex];
            startIndex++;
            endIndex--;
        }
    }

Algoritmo:1).Inverti ogni parola della stringa.2). Stringa risultante inversa.

public class Solution {
public String reverseWords(String p) {
   String reg=" ";
  if(p==null||p.length()==0||p.equals(""))
{
    return "";
}
String[] a=p.split("\\s+");
StringBuilder res=new StringBuilder();;
for(int i=0;i<a.length;i++)
{

    String temp=doReverseString(a[i]);
    res.append(temp);
    res.append(" ");
}
String resultant=doReverseString(res.toString());
System.out.println(res);
return resultant.toString().replaceAll("^\\s+|\\s+$", ""); 
}


public String doReverseString(String s)`{`


char str[]=s.toCharArray();
int start=0,end=s.length()-1;
while(start<end)
{
char temp=str[start];
str[start]=str[end];
str[end]=temp;
start++;
end--;
}
String a=new String(str);
return a;

}

public static void main(String[] args)
{
Solution r=new Solution();
String main=r.reverseWords("kya hua");
//System.out.println(re);
System.out.println(main);
}
}

Una battuta:

l="Is this as expected ??"
" ".join(each[::-1] for each in l[::-1].split())

Produzione:

'?? expected as this Is'

L'algoritmo per risolvere questo problema si basa su un processo in due fasi, la prima fase invertirà le singole parole della stringa, quindi nella seconda fase invertirà l'intera stringa.L'implementazione dell'algoritmo richiederà tempo O(n) e complessità spaziale O(1).

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

      void reverseStr(char* s, int start, int end);

      int main()
      {
              char s[] = "This is test string";

              int start = 0;
              int end = 0;
              int i = 0;

              while (1) {

              if (s[i] == ' ' || s[i] == '\0')
              {
                    reverseStr(s, start, end-1);
                    start = i + 1;
                    end = start;
              }
              else{
                    end++;
              }

              if(s[i] == '\0'){
                   break;
              }
              i++;
      }

      reverseStr(s, 0, strlen(s)-1);
      printf("\n\noutput= %s\n\n", s);

      return 0;
  }

  void reverseStr(char* s, int start, int end)
  {
     char temp;
     int j = end;
     int i = start;

     for (i = start; i < j ; i++, j--) {
          temp = s[i];
          s[i] = s[j];
          s[j] = temp;
     }
 }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top