Reverse the ordering of words in a string

后端 未结 30 4185
青春惊慌失措
青春惊慌失措 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 11:01

    Here is the Java Implementation:

    public static String reverseAllWords(String given_string)
    {
        if(given_string == null || given_string.isBlank())
            return given_string;
    
        char[] str = given_string.toCharArray();
        int start = 0;
    
        // Reverse the entire string
        reverseString(str, start, given_string.length() - 1);
    
        // Reverse the letters of each individual word
        for(int end = 0; end <= given_string.length(); end++)
        {
            if(end == given_string.length() || str[end] == ' ')
            {
                reverseString(str, start, end-1);
                start = end + 1;
            }
        }
        return new String(str);
    }
    
    // In-place reverse string method
    public static void reverseString(char[] str, int start, int end)
    {
        while(start < end)
        {
            char temp = str[start];
            str[start++] = str[end];
            str[end--] = temp;
        }
    }
    

提交回复
热议问题