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类中的相关内容,可以发现是很适合解决这个问题的。

解决上述问题,相当于用两个标志,两个标志之间就是一个单词,然后从后向前看,首先判断当前的是不是空格,如果是,则把两者定位在空格处(这时候i--,而j不用动,substring()的特性),如果当前不是空格,则判断当前的是字母的下一位

是不是空格,如果是则在字符串构建器末尾加空格(此处的i==0的判断,主要是和里面的判断一起用的,以防止只有一个字母的时候),如果上面条件都不满足,那么就把当前的字母加入到字符串构建器中。

Leetcode 详解(ReverseWords)的更多相关文章

  1. 由Leetcode详解算法 之 动态规划(DP)

    因为最近一段时间接触了一些Leetcode上的题目,发现许多题目的解题思路相似,从中其实可以了解某类算法的一些应用场景. 这个随笔系列就是我尝试的分析总结,希望也能给大家一些启发. 动态规划的基本概念 ...

  2. Leetcode 详解(股票交易日)(动态规划DP)

    问题描述: 在股市的交易日中,假设最多可进行两次买卖(即买和卖的次数均小于等于2),规则是必须一笔成交后进行另一笔(即买-卖-买-卖的顺序进行).给出一天中的股票变化序列,请写一个程序计算一天可以获得 ...

  3. Leetcode详解Maximum Sum Subarray

    Question: Find the contiguous subarray within an array (containing at least one number) that has the ...

  4. Leetcode 详解(Substing without repeats character)

    Given a string, find the length of the longest substring without repeating characters. Examples: Giv ...

  5. Leetcode 详解(Valid Number)

    Validate if a given string is numeric. Some examples:"0" => true" 0.1 " => ...

  6. Leetcode 详解(Implement strstr)

    Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle ...

  7. Leetcode 详解(valid plindrome)

    Question: Given a string, determine if it is a palindrome, considering only alphanumeric characters ...

  8. The Skyline Problem leetcode 详解

    class Solution { public: vector<pair<int, int>> getSkyline(vector<vector<int>&g ...

  9. LeetCode(42.接雨水)多解法详解

    接雨水解法详解: 题目: 基本思路:从图上可以看出要想接住雨水,必须是凹字形的,也就是当前位置的左右两边必须存在高度大于它的地方,所以我们要想知道当前位置最多能存储多少水,只需找到左边最高处max_l ...

随机推荐

  1. window7 x64 path

    %SystemRoot%\system32; %SystemRoot%; %SystemRoot%\System32\Wbem; %SYSTEMROOT%\System32\WindowsPowerS ...

  2. JavaScript中数组迭代方法(jquery)

    var arr = [1,2,4,5,6]; //1.forEach(让数组中的每一项做一件事)arr.forEach(function(item,index){    console.log(ite ...

  3. JQuery获取浏览器窗口的可视区域高度和宽度,滚动条高度

    alert($(window).height()); //浏览器时下窗口可视区域高度 alert($(document).height()); //浏览器时下窗口文档的高度 alert($(docum ...

  4. Java GUI编程

    ----基础 // 创建一个窗体对象        JFrame frame = new JFrame();        // 设置窗口大小        frame.setSize(300, 20 ...

  5. Maven 配置 Selenium + testNG + reportNG 运行环境

    .markdown-preview:not([data-use-github-style]) { padding: 2em; font-size: 1.2em; color: rgb(56, 58, ...

  6. Openfire用户密码加密解密

    需求要求审核过程中都用匿名进行用户注册登录,注册用户审核通过后才使用openfire内置表 如何做到用户密码统一 Openfire是通过org.jivesoftware.util.Blowfish.j ...

  7. 让PHP开发者事半功倍的十大技巧

    如果你使用一面大镜子作为冲浪板会发生什么?或许你会在较短的时间内征服海浪,但是你肯定从内心深处明白,这不是冲浪的正确选择.同样的道理也适用于PHP编程,尽管这样的类比听起来有一些古怪.我们经常听到有人 ...

  8. About next_permutation

    哈哈没错这个又是我们C++党的语言优势之一,用这个函数可以求当前排序的下一个排序,也就是说可以方便的求全排列,用这个函数需要用到algorithm这个头文件. 与这个函数相反的是prev_permut ...

  9. mysql字符串函数(转载)

    对于针对字符串位置的操作,第一个位置被标记为1. ASCII(str) 返回字符串str的 最左面字符的ASCII代码值.如果str是空字符串, 返回0.如果str是NULL,返回NULL. mysq ...

  10. mysql-5.7.9安装

    版本:mysql-5.7.9-linux-glibc2.5-x86_64.tar.gz(编译版本) 解压: tar -zxvf mysql-5.7.9-linux-glibc2.5-x86_64.ta ...