Java for LeetCode 151 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".

解题思路:

本题方法多多,最简单的方式直接按“ ” spilt即可,JAVA实现如下:

    public String reverseWords(String s) {
		if (s == null || s.length() == 0)
			return s;
		String[] str = s.split(" ");
		StringBuilder sb = new StringBuilder();
		for (int i = str.length - 1; i >= 0; i--)
			if (str[i].length() >= 1)
				sb.append(str[i] + " ");
		if (sb.length() > 1)
			sb.deleteCharAt(sb.length() - 1);
		return sb.toString();
    }

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。