Reverse Words in a String I

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

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

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.
分析:
先取出多余的white space, 然后再进行(A^TB^T)^T = BA的转换。
 public class Solution {
public String reverseWords(String s) {
if (s == null || s.length() < ) return s;
int i = ;
StringBuilder sb = new StringBuilder();
while (i < s.length()) {
StringBuilder temp = new StringBuilder();
while(i < s.length() && !(s.charAt(i) == ' ')) {
temp.insert(, s.charAt(i));
i++;
}
if (temp.length() != ) {
sb.append(temp.toString());
sb.append(' ');
}
while(i < s.length() && s.charAt(i) == ' ') {
i++;
}
}
if (sb.length() > ) {
sb.deleteCharAt(sb.length() - );
}
char[] arr = sb.toString().toCharArray();
reverse(arr); return new String(arr);
} public void reverse(char[] arr) {
int i = , j = arr.length - ;
while (i < j) {
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
}

 Reverse Words in a String II

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Note: In the string, each word is separated by single space and there will not be any extra space in the string.

 public class Solution {
public String reverseWords(String s) {
char[] ca = s.toCharArray();
int start = ;
for (int i = ; i <= ca.length; i++) {
if (i == ca.length || ca[i] == ' ') {
reverse(ca, start, i - );
start = i + ;
}
}
return new String(ca);
} private void reverse(char[] ca, int i, int j) {
for (; i < j; i++, j--) {
char tmp = ca[i];
ca[i] = ca[j];
ca[j] = tmp;
}
}
}

Reverse Words in a String I & Reverse Words in a String II的更多相关文章

  1. 给String添加reverse方法

    我们知道Array有个reverse方法,String则没有,但可以Array来实现,字符串有个split方法可以轻易的将String转换为Array. String.prototype.revers ...

  2. [LeetCode] 344 Reverse String && 541 Reverse String II

    原题地址: 344 Reverse String: https://leetcode.com/problems/reverse-string/description/ 541 Reverse Stri ...

  3. Convert string to binary and binary to string in C#

    String to binary method: public static string StringToBinary(string data) { StringBuilder sb = new S ...

  4. [转] 请别再拿“String s = new String("xyz");创建了多少个String实例”来面试了吧

    这帖是用来回复高级语言虚拟机圈子里的一个问题,一道Java笔试题的. 本来因为见得太多已经吐槽无力,但这次实在忍不住了就又爆发了一把.写得太长干脆单独开了一帖. 顺带广告:对JVM感兴趣的同学们同志们 ...

  5. JAVA中List转换String,String转换List,Map转换String,String转换Map之间的转换类

    <pre name="code" class="java"></pre><pre name="code" cl ...

  6. Java中String直接赋字符串和new String的区别

    解析Java中的String对象的数据类型 1. String是一个对象.  因为对象的默认值是null,所以String的默认值也是null:但它又是一种特殊的对象,有其它对象没有的一些特性. 2. ...

  7. perl malformed JSON string, neither tag, array, object, number, string or atom, at character offset

    [root@wx03 ~]# cat a17.pl use JSON qw/encode_json decode_json/ ; use Encode; my $data = [ { 'name' = ...

  8. String的内存模型,为什么String被设计成不可变的

    String是Java中最常用的类,是不可变的(Immutable), 那么String是如何实现Immutable呢,String为什么要设计成不可变呢? 前言 关于String,收集一波基础,来源 ...

  9. Java string和各种格式互转 string转int int转string

    Java string和各种格式互转 string转int int转string 简单收集记录下 其他类型转String String s = String.valueOf( value); // 其 ...

  10. Realm 处理List<String> 问题 Type parameter 'java.lang.String' is not within its bound; should implement 'io.realm.RealmModel

    public class InitAppBean extends RealmObject { private String sapling; private String logistics; pri ...

随机推荐

  1. [HNOI2005]狡猾的商人 ,神奇做法——贪心

    洛谷P2294 [HNOI2005]狡猾的商人 ,神奇做法--贪心 看到大牛都是写的差分约束或带权并查集,本蒟蒻都不太会(还是用差分约束过了的QAQ),但是想出一种贪心的策略,运用神奇的优先队列实现. ...

  2. Qtree3题解(树链剖分+线段树+set)

    外话:最近洛谷加了好多好题啊...原题入口 这题好像是SPOJ的题,挺不错的.看没有题解还是来一篇... 题意 很易懂吧.. 题解 我的做法十分的暴力:树链剖分(伪)+线段树+ std :: set ...

  3. SharePoint 2013 批量导入、删除帐号

    删除一个group里所有的帐号: cls ########################### # "Enter the site URL here" $SITEURL = &q ...

  4. 洛谷 P2887 [USACO07NOV]防晒霜Sunscreen 解题报告

    P2887 [USACO07NOV]防晒霜Sunscreen 题目描述 To avoid unsightly burns while tanning, each of the C (1 ≤ C ≤ 2 ...

  5. 洛谷 P2158 [SDOI2008]仪仗队 解题报告

    P2158 [SDOI2008]仪仗队 题目描述 作为体育委员,C君负责这次运动会仪仗队的训练.仪仗队是由学生组成的N * N的方阵,为了保证队伍在行进中整齐划一,C君会跟在仪仗队的左后方,根据其视线 ...

  6. PendingIntent的使用

    1, 构造intent Intent mIntent = new Intent("android.intent.action.MAIN"); ComponentName comp ...

  7. poco logging

    http://pocoproject.org/slides/110-Logging.pdf

  8. python之配置日志的几种方式

    作为开发者,我们可以通过以下3种方式来配置logging: 1)使用Python代码显式的创建loggers, handlers和formatters并分别调用它们的配置函数: 2)创建一个日志配置文 ...

  9. k8s 常用命令汇集

    通过yaml文件创建: kubectl create -f xxx.yaml (不建议使用,无法更新,必须先delete) kubectl apply -f xxx.yaml (创建+更新,可以重复使 ...

  10. Hbase记录-HBaseAdmin类

    HBaseAdmin是一个类表示管理.这个类属于org.apache.hadoop.hbase.client包.使用这个类,可以执行管理员任务.使用Connection.getAdmin()方法来获取 ...