• 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.感觉考察的东西不多,主要在于细节字符串中空格的处理还有就是字符串相关函数的应用

  • 相关阅读:
    springboot + driud连接池踩的坑____新手学习
    tomcat的安装
    无限极分类
    javascript ECMAscript 和node.js commonJs之间的关系
    变量名,引用和地址
    java中闭包的理解
    thinkphp 模型的curd
    thinkphp之migration 迁移文件的使用
    验证ArrayList是线程不安全的集合
    一个java小程序,盗取插入的U盘中的数据。
  • 原文地址:https://www.cnblogs.com/zhangminghui/p/4089401.html
Copyright © 2020-2023  润新知