Reverse Words in a String I & Reverse Words in a String II
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
".
- 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.
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的更多相关文章
- 给String添加reverse方法
我们知道Array有个reverse方法,String则没有,但可以Array来实现,字符串有个split方法可以轻易的将String转换为Array. String.prototype.revers ...
- [LeetCode] 344 Reverse String && 541 Reverse String II
原题地址: 344 Reverse String: https://leetcode.com/problems/reverse-string/description/ 541 Reverse Stri ...
- Convert string to binary and binary to string in C#
String to binary method: public static string StringToBinary(string data) { StringBuilder sb = new S ...
- [转] 请别再拿“String s = new String("xyz");创建了多少个String实例”来面试了吧
这帖是用来回复高级语言虚拟机圈子里的一个问题,一道Java笔试题的. 本来因为见得太多已经吐槽无力,但这次实在忍不住了就又爆发了一把.写得太长干脆单独开了一帖. 顺带广告:对JVM感兴趣的同学们同志们 ...
- JAVA中List转换String,String转换List,Map转换String,String转换Map之间的转换类
<pre name="code" class="java"></pre><pre name="code" cl ...
- Java中String直接赋字符串和new String的区别
解析Java中的String对象的数据类型 1. String是一个对象. 因为对象的默认值是null,所以String的默认值也是null:但它又是一种特殊的对象,有其它对象没有的一些特性. 2. ...
- 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' = ...
- String的内存模型,为什么String被设计成不可变的
String是Java中最常用的类,是不可变的(Immutable), 那么String是如何实现Immutable呢,String为什么要设计成不可变呢? 前言 关于String,收集一波基础,来源 ...
- Java string和各种格式互转 string转int int转string
Java string和各种格式互转 string转int int转string 简单收集记录下 其他类型转String String s = String.valueOf( value); // 其 ...
- 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 ...
随机推荐
- 配置AD RMS及SharePoint 2013 IRM问题解决及相关资源
最近配置AD RMS及SharePoint 2013 IRM遇到几个问题: 1. RMS配置好后,client端连不上, 一直要求输入用户名和密码. 后来换了台不是SP的机器,并用内部DB,搞定. ...
- httpd.yml实例
httpd.ymlapiVersion: apps/v1beta1kind: Deploymentmetadata: name: httpdspec: replicas: 4 template: me ...
- 分别用postman和python做post请求接口功能测试
前几天,在做一个post请求的接口功能测试的时候,发现数据始终无法入库, 认真加仔细检查了请求的url.方式.参数,均没有问题 找到技术确认,原来是需要传json格式数据 在头信息中加上类型,body ...
- 深入理解Adaboost算法
理解算法确实是欲速则不达,唯有一步一步慢慢看懂,然后突然觉得写的真的太好了,那才是真的有所理解了. Adaboost的两点关键点: 1. 如何根据弱模型的表现更新训练集的权重: 2. 如何根据弱模型的 ...
- 1063. Set Similarity
Given two sets of integers, the similarity of the sets is defined to be Nc/Nt*100%, where Nc is the ...
- 关于:HTTP Header -> Content-Type: text/plain Cache-Control: no-cache IE浏览器弹出错误下载对话
下午遇到一个很奇怪的现象,一个网址: http://192.168.1.3/login?action=a&fr=b.com 注意网址后面的参数形式,action参数在前,最后一个参数值的尾部含 ...
- SQL语句中 int 溢出 + Asp语句中 Long 溢出
晚上5点多,同事在QQ告诉我,一个用户向他反应,在他登录的时候显示错误信息,我们在管理平台查看该用户的基本信息时,也显示错误信息. 经过初步分析,原来是在执行 SQL语句的时候发生Int溢出: sql ...
- isinstance和issubclass,__getattribute__,__getitem__,__setitem__,delitem__,__str__(三十五)
isinstance(obj,cls)检查是否obj是否是类 cls 的对象 issubclass(sub, super)检查sub类是否是 super 类的派生类 class Foo: def __ ...
- Android Support Library 是什么?
这两天刚开始学习安卓,这里记录下这两天遇到的一些小问题. 首先先贴一个安卓 API 等级. 官方地址:https://developer.android.com/about/dashboards/ ( ...
- PowerDesigner使用(设置继承,实现)
1.File—New Mode 2添加4个class,1个接口(基本的添加工具都在这里面) 3.class1的设置名字,设置方法 3.设置继承,实现 4.编辑class2,class3继承父类的属性. ...