Reverse Words

来源:互联网 发布:淘宝老顾客营销方案 编辑:程序博客网 时间:2024/06/05 00:20

Reverse Words

Write a function that reverses the order of the words in a string. For example, your function should transform the string “Do or do not, there is no try.” to “try. no is there not, do or Do”. Assume that all words are space delimited and treat punctuation the same as letters.

class Solution {  public static String reverseWords(char[] str) {    if (str == null || str.length == 0)        return null;        reverseStr(str, 0, str.length - 1);        int start = 0;    int end = 0;    while (end < str.length) {    if (str[end] != ' ') {      start = end;            while ( end < str.length && str[end] != ' ')        end++;            end--;      reverseStr(str, start, end);          }     end++;    }        return  new String(str);  }      private static void reverseStr(char[] str, int start, int end) {        while (end > start) {           char temp = str[start];      str[start] = str[end];      str[end] = temp;            end--;      start++;    }      }  public static void main(String[] args) {    String str = "Do or do not, there is no try.";    char[] ch = str.toCharArray();    System.out.print(reverseWords(ch));  }}


0 0
原创粉丝点击