C++实现LeetCode(151.翻转字符串中的单词)

[LeetCode] 151.Reverse Words in a String 翻转字符串中的单词

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 in-place in O(1) space.

click to show clarification.

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.

这道题让我们翻转字符串中的单词,题目中给了我们写特别说明,如果单词之间遇到多个空格,只能返回一个,而且首尾不能有单词,并且对C语言程序员要求空间复杂度为O(1),所以我们只能对原字符串s之间做修改,而不能声明新的字符串。那么我们如何翻转字符串中的单词呢,我们的做法是,先整个字符串整体翻转一次,然后再分别翻转每一个单词(或者先分别翻转每一个单词,然后再整个字符串整体翻转一次),此时就能得到我们需要的结果了。那么这里我们需要定义一些变量来辅助我们解题,storeIndex表示当前存储到的位置,n为字符串的长度。我们先给整个字符串反转一下,然后我们开始循环,遇到空格直接跳过,如果是非空格字符,我们此时看storeIndex是否为0,为0的话表示第一个单词,不用增加空格;如果不为0,说明不是第一个单词,需要在单词中间加一个空格,然后我们要找到下一个单词的结束位置我们用一个while循环来找下一个为空格的位置,在此过程中继续覆盖原字符串,找到结束位置了,下面就来翻转这个单词,然后更新i为结尾位置,最后遍历结束,我们剪裁原字符串到storeIndex位置,就可以得到我们需要的结果,代码如下:

C++ 解法一:

class Solution {
public:
    void reverseWords(string &s) {
        int storeIndex = 0, n = s.size();
        reverse(s.begin(), s.end());
        for (int i = 0; i < n; ++i) {
            if (s[i] != ' ') {
                if (storeIndex != 0) s[storeIndex++] = ' ';
                int j = i;
                while (j < n && s[j] != ' ') s[storeIndex++] = s[j++];
                reverse(s.begin() + storeIndex - (j - i), s.begin() + storeIndex);
                i = j;
            }
        }
        s.resize(storeIndex);
    }
};

Java解法一:

public class Solution {
    public String reverseWords(String s) {
        int storeIndex = 0, n = s.length();
        StringBuilder sb = new StringBuilder(s).reverse();
        for (int i = 0; i < n; ++i) {
            if (sb.charAt(i) != ' ') {
                if (storeIndex != 0) sb.setCharAt(storeIndex++, ' ');
                int j = i;
                while (j < n && sb.charAt(j) != ' ') sb.setCharAt(storeIndex++, sb.charAt(j++));
                String t = new StringBuilder(sb.substring(storeIndex - (j - i), storeIndex)).reverse().toString();
                sb.replace(storeIndex - (j - i), storeIndex, t);
                i = j;
            }
        }
        sb.setLength(storeIndex);
        return sb.toString();
    }
}

下面我们来看使用字符串流类stringstream的解法,我们先把字符串装载入字符串流中,然后定义一个临时变量tmp,然后把第一个单词赋给s,这里需要注意的是,如果含有非空格字符,那么每次>>操作就会提取连在一起的非空格字符,那么我们每次将其加在s前面即可;如果原字符串为空,那么就不会进入while循环;如果原字符串为许多空格字符连在一起,那么第一个>>操作就会提取出这些空格字符放入s中,然后不进入while循环,这时候我们只要判断一下s的首字符是否为空格字符,是的话就将s清空即可,参见代码如下:

C++ 解法二:

class Solution {
public:
    void reverseWords(string &s) {
        istringstream is(s);
        string tmp;
        is >> s;
        while(is >> tmp) s = tmp + " " + s;
        if(!s.empty() && s[0] == ' ') s = "";
    }
};

下面这种方法也是使用stringstream来做,但是我们使用了getline来做,第三个参数是设定分隔字符,我们用空格字符来分隔,这个跟上面的>>操作是有不同的,每次只能过一个空格字符,如果有多个空格字符连在一起,那么t会赋值为空字符串,所以我们在处理t的时候首先要判断其是否为空,是的话直接跳过,参见代码如下:

C++ 解法三:

class Solution {
public:
    void reverseWords(string &s) {
        istringstream is(s);
        s = "";
        string t = "";
        while (getline(is, t, ' ')) {
            if (t.empty()) continue;
            s = (s.empty() ? t : (t + " " + s));
        }
    }
};

而如果我们使用Java的String的split函数来做的话就非常简单了,没有那么多的幺蛾子,简单明了,我们首先将原字符串调用trim()来去除冗余空格,然后调用split()来分隔,分隔符设为"\\s+",这其实是一个正则表达式,\\s表示空格字符,+表示可以有一个或多个空格字符,那么我们就可以把单词分隔开装入一个字符串数组中,然后我们从末尾开始,一个个把单词取出来加入结果res中,并且单词之间加上空格字符,注意我们把第一个单词留着不取,然后返回的时候再加上即可,参见代码如下:

Java解法二:

public class Solution {
    public String reverseWords(String s) {
        String res = "";
        String[] words = s.trim().split("\\s+");
        for (int i = words.length - 1; i > 0; --i) {
            res += words[i] + " ";
        }
        return res + words[0];
    }
}

下面这种方法就更加的简单了,疯狂的利用到了Java的内置函数,这也是Java的强大之处,注意这里的分隔符没有用正则表达式,而是直接放了个空格符进去,后面还是有+号,跟上面的写法得到的效果是一样的,然后我们对字符串数组进行翻转,然后调用join()函数来把字符串数组拼接成一个字符串,中间夹上空格符即可,参见代码如下:

Java解法三:

public class Solution {
    public String reverseWords(String s) {
        String[] words = s.trim().split(" +");
        Collections.reverse(Arrays.asList(words));
        return String.join(" ", words);
    }
}

类似题目:

Reverse Words in a String II 

参考资料:

https://discuss.leetcode.com/topic/3298/in-place-simple-solution

https://discuss.leetcode.com/topic/2742/my-accepted-java-solution

https://discuss.leetcode.com/topic/11785/java-3-line-builtin-solution

https://discuss.leetcode.com/topic/10199/5-lines-c-using-stringstream

到此这篇关于C++实现LeetCode(151.翻转字符串中的单词)的文章就介绍到这了,更多相关C++实现翻转字符串中的单词内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • C++实现LeetCode(150.计算逆波兰表达式)

    [LeetCode] 150.Evaluate Reverse Polish Notation 计算逆波兰表达式 Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. Note: Division between two integ

  • C++实现LeetCode(148.链表排序)

    [LeetCode] 148. Sort List 链表排序 Sort a linked list in O(n log n) time using constant space complexity. Example 1: Input: 4->2->1->3 Output: 1->2->3->4 Example 2: Input: -1->5->3->4->0 Output: -1->0->3->4->5 常见排序方法有

  • C++实现LeetCode(146.近最少使用页面置换缓存器)

    [LeetCode] 146. LRU Cache 最近最少使用页面置换缓存器 Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put. get(key) - Get the value (will always be positive) of the key if the key exist

  • C++实现LeetCode(154.寻找旋转有序数组的最小值之二)

    [LeetCode] 154. Find Minimum in Rotated Sorted Array II 寻找旋转有序数组的最小值之二 Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e.,  [0,1,2,4,5,6,7] might become  [4,5,6,7,0,1,2]). Find the minimum element. Th

  • C++实现LeetCode(147.链表插入排序)

    [LeetCode] 147. Insertion Sort List 链表插入排序 Sort a linked list using insertion sort. A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list. With each iteration one element (red) is

  • C++实现LeetCode(152.求最大子数组乘积)

    [LeetCode] 152. Maximum Product Subarray 求最大子数组乘积 Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product. Example 1: Input: [2,3,-2,4] Output: 6 Explanation: [2,3] has

  • C++实现LeetCode(153.寻找旋转有序数组的最小值)

    [LeetCode] 153. Find Minimum in Rotated Sorted Array 寻找旋转有序数组的最小值 Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e.,  [0,1,2,4,5,6,7] might become  [4,5,6,7,0,1,2]). Find the minimum element. You may

  • C++实现LeetCode(149.共线点个数)

    [LeetCode] 149. Max Points on a Line 共线点个数 Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. Example 1: Input: [[1,1],[2,2],[3,3]] Output: 3 Explanation: ^ | |        o |     o |  o   +------------->

  • C++实现LeetCode(151.翻转字符串中的单词)

    [LeetCode] 151.Reverse Words in a String 翻转字符串中的单词 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 in-p

  • C++实现LeetCode(557.翻转字符串中的单词之三)

    [LeetCode] 557.Reverse Words in a String III 翻转字符串中的单词之三 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 conte

  • C++实现LeetCode(186.翻转字符串中的单词之二)

    [LeetCode] 186. Reverse Words in a String II 翻转字符串中的单词之二 Given an input string , reverse the string word by word.  Example: Input:  ["t","h","e"," ","s","k","y"," ","i&qu

  • C语言如何实现翻转字符串中的单词

    目录 C语言翻转字符串中的单词 另外开辟一个空间,来存放翻转的字符串 直接在原数组上进行操作 C语言字符串各单词的反转 思路 代码实现 代码编译 调试输出 C语言翻转字符串中的单词 另外开辟一个空间,来存放翻转的字符串 单词之间是以空格间隔的,所以我们翻转需要一个一个字符进行翻转,我们需要找寻空格,找到空格表示一个字符已经找到,进行以下的步骤: 1. 首先获取原字符串的长度,申请一个长度+1的空间,因为还需要一个结束符. 2. 定义一个变量i,初始化为0,用i进行字符串的遍历,定义一个start

  • 利用golang的字符串解决leetcode翻转字符串里的单词

    题目 给定一个字符串,逐个翻转字符串中的每个单词. 示例 1: 输入: "the sky is blue" 输出: "blue is sky the" 示例 2: 输入: " hello world! " 输出: "world! hello" 解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括. 示例 3: 输入: "a good example" 输出: "exampl

  • python3翻转字符串里的单词点的实现方法

    给定一个字符串,逐个翻转字符串中的每个单词. 说明: 无空格字符构成一个 单词 . 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括. 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个. 示例 1: 输入:"the sky is blue" 输出:"blue is sky the" 示例 2: 输入:" hello world! " 输出:"world! hello" 解释:输入字符串可以在前

  • php ucwords() 函数将字符串中每个单词的首字符转换为大写(实现代码)

    php ucwords() 函数将字符串中每个单词的首字符转换为大写, 本文章向码农介绍php ucwords() 函数的基本使用方法和实例,感兴趣的码农可以参考一下. 定义和用法 ucwords() 函数把字符串中每个单词的首字符转换为大写. 注释:该函数是二进制安全的. 相关函数: lcfirst() - 把字符串中的首字符转换为小写 strtolower() - 把字符串转换为小写 strtoupper() - 把字符串转换为大写 ucfirst() - 把字符串中的首字符转换为大写 语法

  • php返回字符串中所有单词的方法

    本文实例讲述了php返回字符串中所有单词的方法.分享给大家供大家参考.具体分析如下: 这段代码返回字符串中的所有单词,当$distinct=true时去除重复元素.代码如下: <?php function split_en_str($str,$distinct=true) { preg_match_all('/([a-zA-Z]+)/',$str,$match); if ($distinct == true) { $match[1] = array_unique($match[1]); } so

  • C语言左旋转字符串与翻转字符串中单词顺序的方法

    左旋转字符串 题目: 定义字符串的左旋转操作:把字符串前面的若干个字符移动到字符串的尾部. 如把字符串 abcdef  左旋转 2  位得到字符串 cdefab.请实现字符串左旋转的函数. 要求时间对长度为 n  的字符串操作的复杂度为 O(n),辅助内存为 O(1). 分析: 网上看到解法很多种,就不详细说明了. 我采用的是数组不对称的交换时间复杂度应该是O(n). 代码实现(GCC编译通过): #include "stdio.h" #include "stdlib.h&q

  • c语言输出字符串中最大对称子串长度的3种解决方案

    问题描述: 输入一个字符串,输出该字符串中最大对称子串的长度.例如输入字符串:"avvbeeb",该字符串中最长的子字符串是"beeb",长度为4,因而输出为4. 解决方法:中序遍历 一,全遍历的方法: 1.全遍历的方法,复杂度O(n3); 2.遍历原字符串的所有子串,然后判断每个子串是否对称: 实现方法是:我们让一个指针i从头至尾遍历,我们用另一个指针j从j=i+1逐一指向i后面的所有字符.就实现了原串的所有子串的遍历(子串为指针i到j中间的部分);最后判断得到的

随机推荐