开发者

Reverse the orders of words--time complexity?

Input: "My Name is Pritam" Output: "Pritam is Name My"

I have written this so far, but I'm bit confused with time complexity

public string ReverseWordsInAString(string str)
    {
        char[] temp = str.ToCharArray();
        int startIndex = 0;
        int endIndex = str.Length - 1;
        temp = ReverseString(temp, startIndex, endIndex);
        endIndex = 0;
        foreach (char c in temp)
        {
            if(c == ' ')
            {
                temp = ReverseString(temp, startIndex, endIndex-1);
                startIndex = endIndex + 1;
            }
            if (endIndex == str.Length-1)
            {
            开发者_运维知识库    temp = ReverseString(temp, startIndex, endIndex);
            }
            endIndex++;
        }
        str = new string(temp);
        return str;
    }

    public char[] ReverseString(char[] chr, int start, int end)
    {
        while (start < end)
        {
            char temp = chr[start];
            chr[start] = chr[end];
            chr[end] = temp;
            start++;
            end--;
        }
        return chr;
    }

When I call ReverseString method from a for loop I think it no more a O(n) solution. Please correct me if I'm wrong. Does anyone have any better solution.


in Java

String str= "My Name is Pritam";
String arr[] = str.split(" ");
for(int i = arr.length-1 ; i >=0 ; i--){
   System.out.println(arr[i]);
}


Your code is O(n). You can see this by looking at the number of swaps each element is involved in, which is 2 (once for the initial reverse of the entire string, second for the word-wise reversal). In addition the foreach loop iterates over each element exactly once.


In Ruby:

sentence = "My name is Pritam"
print sentence.split(" ").reverse.join(" ")


In C;

char *s = "My Name is Pritam", *t = s + strlen(s), *end = strchr(s,' ')-1;
while( t != end )
{
  *(t = strrchr(t,' ')) = '\0';
  printf( "%s ", --t+2 );
}
printf( "%s", s );


Possible duplicate, I had asked a similar question some time back. But the responses I received were very interesting, actually it did change the way complexity should be thought about ;).... Time Complexity


Split the string and push it to a stack . Pop elements from stack and add it to a new string. Requires extra space,but just posted because it could be a easy way to implement string reverse

public class StringReverse {

public static void main (String args[]){

    String input = "My name is Pritam";

    Stack<String> stack  = new Stack<String>();

    String[] strings= input.split(" ");

    for(String str :strings){
        stack.push(str);
    }

    String reverse = "" ;

    while(!stack.isEmpty()){
        reverse = reverse + " " + stack.pop();
    }

    System.out.println(reverse);
}

}


in Python,

sentence = "My name is Pritam"
' '.join(sentence.split(" ")[::-1])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜