zoukankan      html  css  js  c++  java
  • 557. Reverse Words in a String III

    Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

    Example 1:

    Input: "Let's take LeetCode contest"
    Output: "s'teL ekat edoCteeL tsetnoc"
    

     Note: In the string, each word is separated by single space and there will not be any extra space in the string.

    题目含义:翻转每一个单词,单子之间的位置保持不变

     方法一:

     1     public String reverseWords(String s) {
     2         String[] words = s.split(" ");
     3         StringBuilder result = new StringBuilder();
     4         for (String word:words)
     5         {
     6             String newWord = new StringBuilder(word).reverse().toString();
     7             result.append(newWord).append(" ");
     8         }
     9         return result.toString().trim();        
    10     }

    方法二:

     1 public String reverseWords(String s) 
     2 {
     3     char[] s1 = s.toCharArray();
     4     int i = 0;
     5     for(int j = 0; j < s1.length; j++)
     6     {
     7         if(s1[j] == ' ')
     8         {
     9             reverse(s1, i, j - 1);
    10             i = j + 1;
    11         }
    12     }
    13     reverse(s1, i, s1.length - 1);
    14     return new String(s1);
    15 }
    16 
    17 public void reverse(char[] s, int l, int r)
    18 {
    19     while(l < r)
    20     {
    21         char temp = s[l];
    22         s[l] = s[r];
    23         s[r] = temp;
    24         l++; r--;
    25     }
    26 }
  • 相关阅读:
    ajax的post请求
    ajax的get请求
    浏览器缓存机制
    php和cookie
    php表单(2)
    php和表单(1)
    枚举for/in
    .Matrix-Beta冲刺的汇总博客
    .Matrix汇总博客
    小黄衫获得的感想
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7680431.html
Copyright © 2011-2022 走看看