博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Reverse Words in a String
阅读量:4074 次
发布时间:2019-05-25

本文共 1444 字,大约阅读时间需要 4 分钟。

Reverse Words in a String

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

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

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

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.
Java代码:

public class Solution {    public String reverseWords(String s) {        String s1 = s.trim();		if (s1.length() == 0)			return s1;		String[] word = s.split("\\s+");		int len = word.length;		StringBuilder sb = new StringBuilder();		if (word[0].equals("") || word[len - 1].equals("")) {			if (word[0].equals("") && word[len - 1].equals("")) {				for (int i = len - 2; i > 1; i--) {					sb.append(word[i]);					sb.append(" ");				}				sb.append(word[1]);			} else if (word[0].equals("")) {				for (int i = len - 1; i > 1; i--) {					sb.append(word[i]);					sb.append(" ");				}				sb.append(word[1]);			} else {				for (int i = len - 2; i > 0; i--) {					sb.append(word[i]);					sb.append(" ");				}				sb.append(word[0]);			}		} else {			for (int i = len - 1; i > 0; i--) {				sb.append(word[i]);				sb.append(" ");			}			sb.append(word[0]);		}		return sb.toString();    }}
 

转载地址:http://wvuni.baihongyu.com/

你可能感兴趣的文章
【leetcode】Candy(python)
查看>>
【leetcode】Sum Root to leaf Numbers
查看>>
【leetcode】Pascal's Triangle II (python)
查看>>
如何成为编程高手
查看>>
本科生的编程水平到底有多高
查看>>
Solr及Spring-Data-Solr入门学习
查看>>
python_time模块
查看>>
python_configparser(解析ini)
查看>>
selenium学习资料
查看>>
从mysql中 导出/导入表及数据
查看>>
HQL语句大全(转)
查看>>
几个常用的Javascript字符串处理函数 spilt(),join(),substring()和indexof()
查看>>
javascript传参字符串 与引号的嵌套调用
查看>>
swiper插件的的使用
查看>>
layui插件的使用
查看>>
JS牛客网编译环境的使用
查看>>
9、VUE面经
查看>>
Golang 数据可视化利器 go-echarts ,实际使用
查看>>
mysql 跨机器查询,使用dblink
查看>>
mysql5.6.34 升级到mysql5.7.32
查看>>