• Reverse Words in a String


    leetcode:https://oj.leetcode.com/problems/reverse-words-in-a-string

    今天写了开题报告,有点不太想开那个报告了,没事又去A了一道ACM。这次A的是系统随机推荐的,刚看的时候以为是一个Easy类型的。感觉不太难

    PS:一开始把题目理解错了,以为直接把所有字符Reverse。实际是将单词Reverse,单词里面的不用Reverse。

    Given an input string, reverse the string word by word.

    For example,
    Given s = "the sky is blue",
    return "blue is sky the".

     1 public class Solution_Reserse {
     2     public String reverseWords(String str){
     3         String str_result = "";
     4         String str_word = "";
     5         char array_src[] = str.toCharArray();
     6         char array_word[];
     7         int count = 0;
     8         int i =array_src.length - 1;
     9         int j = i;
    10         boolean isWord = false;        //判断是否有单词
    11         
    12         while(j >= 0){
    13             while(j >= 0 && array_src[j] != ' '){
    14                 count++;
    15                 j--;
    16             }//找出单词长度
    17             array_word = new char[count];//存放单词数组
    18 
    19             while(i >= 0 && array_src[i] != ' '){
    20                 count--;
    21                 array_word[count] = array_src[i];                
    22                 i--;
    23                 isWord = true;
    24             }//单词已按正确顺序放好
    25             if(isWord){
    26                 str_word = new String(array_word);//一个单词字符串
    27                 str_result += str_word + " ";//拼接到结果字符串中
    28             }
    29             
    30             isWord = false;
    31             j--;
    32             i--;
    33         }
    34         if("" == str || " " == str)
    35             return "";
    36         else if(str_result.length() != 0)
    37             str_result = str_result.substring(0, str_result.length() - 1);
    38         return str_result;
    39     }
    40 }

     贴个特别简单的实现

     1 public class Solution_Reserse {
     2     public String reverseWords(String str){
     3         StringBuilder sb = new StringBuilder();
     4         String[] split = str.split("\s+");
     5         int len = split.length;
     6         for(int i=len-1; i>=0; i--){
     7             sb.append(split[i]).append(" ");
     8         }
     9         return sb.toString().trim();
    10     }
    11 }
  • 相关阅读:
    XGBoost原理解析
    变分贝叶斯学习(variational bayesian learning)及重参数技巧(reparameterization trick)
    Tensorflow Probability Distributions 简介
    树形dp--hdu 1520 anniversary party
    线段树II--区间修改
    leetcode---different ways to add parentheses
    线段树
    实现最大堆
    编写支持对齐分配的malloc和free函数
    指针和引用的区别,指针和数组的区别
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4046659.html
Copyright © 2020-2023  润新知