星空网 > 软件开发 > Java

Leetcode 详解(ReverseWords)

Leetcode里面关于字符串的一些问题,描述如下:

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 inO(1) space.

click to show clarification.

Subscribe to see which companies asked this question

解决方案如下:


import java.util.*;import java.io.*;import java.lang.*;public class ReverseWords {    public String reverseWords(String s) {     StringBuilder reversed = new StringBuilder(); //构建一个空的字符串构建器     int j = s.length();    for (int i = s.length() - 1; i >= 0; i--) {        if (s.charAt(i) == ' ') {          j = i;
}
         else if (i == 0 || s.charAt(i - 1) == ' ') { if (reversed.length() != 0) { //当输入只有一个字符的时候,如"a",这时候程序会运行到这一步,但注意此时构建器是没有内容的,因而reversed.length()为0,不满足条件 reversed.append(' '); // 空格也要输进去,但同时要避免两端是空格的情况,那时候是不要输入的。 } reversed.append(s.substring(i, j)); // 注意此处,运用了字串substring,这个和我之前的想法是一致的,即连接在一起的字符串用substring截取下来。这里,截取下来后放入字符串构建器中 } // substring(int i,int j) 返回一个新字符串,这个新字符串包含原始字符串中的位置从i~j-1的部分,注意下标不包括j } return reversed.toString(); // 注意这才是字符串构建器的正确输出格式,返回的是一个与构建器(或称为缓冲器)内容相同的字符串 } /* private String ReWords(String s) { String B=" "; for(int i=0;i<s.length();i++) { //for(int j=i;s.charAt(j)!="";j++); int j=i; while(Character.isLetter(s.charAt(j))&&(j<s.length()))j++; String A=s.substring(i,j); B=A+B; i=j; } return B; } */ public static void main(String[] args){ ReverseWords Reverse = new ReverseWords(); String out_target=Reverse.reverseWords("ab cac cc"); System.out.printf("the output is "+out_target); System.out.println(); }}

总结:注释掉的部分,是我自己的思路,但是行不通,主要体现在:我是采用字符串连接的方式解决这个问题的,这样每次连接字符串都会产生一个心结的String对象,既耗时又浪费空间。并且,思路有点混乱。

cleancode 采用了StringBuilder类,这样就可以避免上诉的问题。可以认真阅读StringBuilder类中的相关内容,可以发现是很适合解决这个问题的。

 




原标题:Leetcode 详解(ReverseWords)

关键词:word

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

tiktok靠谱:https://www.goluckyvip.com/tag/83829.html
tiktok英国本土小店:https://www.goluckyvip.com/tag/83830.html
tiktok英国小店本土:https://www.goluckyvip.com/tag/83831.html
tiktok本土英国小店:https://www.goluckyvip.com/tag/83832.html
tiktok邀请达人:https://www.goluckyvip.com/tag/83833.html
tiktok带货详细流程:https://www.goluckyvip.com/tag/83835.html
月活用户超20亿!万亿市值巨头对中国商家进一步开闸放流 :https://www.kjdsnews.com/a/1836412.html
九寨沟周围必去的景点推荐:https://www.vstour.cn/a/363190.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流