当前位置 : 首页 » 文章分类 :  算法  »  LeetCode.557.Reverse Words in a String III 反转字符串中的单词 III

LeetCode.557.Reverse Words in a String III 反转字符串中的单词 III

题目描述

557 Reverse Words in a String III
https://leetcode-cn.com/problems/reverse-words-in-a-string-iii/
https://leetcode.com/problems/reverse-words-in-a-string-iii/description/

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.

解题过程

这道题一看就想着要用两种方法做,第一种是转为字符数组,完全手动操作,一次遍历,遇到一个单词就调函数逆转,第二种是用java String类操作,先split拆分成单词,然后挨个调方法逆转。

代码如下,手动版调试了几次,String类版还是查着SDK才写完,用到了java8中新增的String.join()方法,还学到了StringBuffer类中就有一个reverse()方法可直接用。

class Solution {
    //手动处理版
    public String reverseWords1(String s) {
        char[] str = s.toCharArray();
        int start=0; //要反转的子串的起始位置
        int length=0; //要反转的子串的长度
        for(int i=0; i<str.length; i++){
            //当前字符非空格,继续往前扫描,同时记录子串长度
            if(str[i] != ' '){
                length++;
            }
            //当前字符为空格,或者是最后一个字符
            if(str[i]==' ' || i==str.length-1){
                if(length>1){//当子串长度大于1时
                    reverse(str, start, start+length-1);//反转子串
                }
                length=0;//长度归零
                start=i+1;//起始位置后移
            }
        }
        return new String(str);
    }

    //反转字符数组str中从start到end的内容
    public char[] reverse(char[] str, int start, int end){
        int i=start, j=end;
        while(i<j){
            char temp=str[i];
            str[i] = str[j];
            str[j] = temp;
            i++;
            j--;
        }
        return str;
    }

    //java方法版
    public String reverseWords(String s) {
        String split[] = s.split(" ",-1);//空格分割字符串,-1会保留空字符串
        for(int i=0; i<split.length; i++){
            StringBuffer stringBuffer = new StringBuffer(split[i]);
            split[i] = stringBuffer.reverse().toString();
        }
        return String.join(" ", split);//空格连接split集合成字符串
    }
}

GitHub代码

algorithms/leetcode/leetcode/_557_ReverseWordsInString3.java
https://github.com/masikkk/algorithms/blob/master/leetcode/leetcode/_557_ReverseWordsInString3.java


上一篇 LeetCode.537.Complex Number Multiplication 复数乘法

下一篇 LeetCode.657.Robot Return to Origin 机器人能否返回原点

阅读
评论
502
阅读预计2分钟
创建日期 2018-01-08
修改日期 2018-01-11
类别

页面信息

location:
protocol:
host:
hostname:
origin:
pathname:
href:
document:
referrer:
navigator:
platform:
userAgent:

评论