zoukankan      html  css  js  c++  java
  • LeetCode之Reverse Words in a String

    1.(原文)问题描述

    Given an input string, reverse the string word by word.
    
    For example,
    Given s = "the sky is blue",
    return "blue is sky the".
    
    click to show clarification.
    
    Clarification:
    What constitutes a word?
    A sequence of non-space characters constitutes a word.
    Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
    How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.
    

     2.问题翻译

    对于一个输入的字符串,逐个词反转这个字符串
    
    例如,
    
    所给的字符串s =  "the sky is blue",
    返回 "blue is sky the".
    
    
    说明:
    
     每个词由什么组成?
    
       由不含空格字符的序列组成每个词
    
     输入的字符串的开头或者结尾能否包含空格?
       
       是的,当然可以。但是在你反转的时候你应该把开头和结尾的字符空格去掉。
    
    如果两个词之间含有多个空格呢?
    
     在反转后的字符串中应该讲他们减少为一个空格。
       
    
         
    

     3.思路分析

      很显然在拿到字符串的时候首先先进行判断是否为空,如果为空应该原样输出;如果不为空则首先需要处理的情况就是考虑到字符串中每个词之间存在多个空格的情况,

    我们需要将这些空格首先变成一个,最后开始处理这个字符串。通过获取字符串数组然后反向输出,在输出的时候拼接空格得到反转后的数组

    4.实现过程

    Solution.java

    package ReverseWords;
    
    public class Solution {
    	
        public String reverseWords(String s) {
        	
        	if(s == null||"".equals(s)){//判断是否为空,为空则直接返回
        		return "";
        	}
        	StringBuffer strBuffer = new StringBuffer();
        	String []tempArray = s.replaceAll("\s{1,}", " ").split(" ");//去除多空格情况然后返回字符数组
        	for(int index = tempArray.length-1;index >= 0;index--){
        		strBuffer.append(tempArray[index]+" ");//拼接反转数组
        	}
        	return strBuffer.toString().trim();
        }
    }
    

      SolutionTest.java

    package ReverseWords;
    
    public class SolutionTest {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		String str = "   a   b ";
    		System.out.println("反转后的字符串是:"+new Solution().reverseWords(str));
    	}
    
    }
    

     5.感觉考察的东西不多,主要在于细节字符串中空格的处理还有就是字符串相关函数的应用

  • 相关阅读:
    【函数】wm_concat包的订制
    【云和恩墨】性能优化:Linux环境下合理配置大内存页(HugePage)
    【技巧】如何使用客户端发布BLOG+如何快速发布微信公众号文章
    【故障处理】队列等待之TX
    【转载】TX
    【转载】Linux磁盘管理:LVM逻辑卷管理
    【索引】Oracle之不可见索引和虚拟索引的比对
    小麦苗微信公众号文章链接地址
    Oracle 11g新特性direct path read引发的系统停运故障诊断处理
    常识之外:全表扫描为何产生大量 db file sequential read 单块读?
  • 原文地址:https://www.cnblogs.com/zhangminghui/p/4089401.html
Copyright © 2011-2022 走看看