朋友的问题:字符串逆置

10 篇文章 0 订阅

一、引言

今天收到了同学发来的一道题,叫我用 C++ 实现:

Problem Statement

The input is an English sentence as a string, we need a function - “function convert($input)” that can transform it as described below and return a new string.

The sentence would contain only alphabet (a-z and A-Z) and space, each word would be separated by exactly one space. There would be no spaces before and after the sentence.

Please return the string with each word spelled in reverse, however, the position of the capitalization of each letter should stay the same for each word.

For example:

Input: Many people spell MySQL incorrectly

Output: Ynam elpoep lleps LqSYM yltcerrocni

这道题的大概意思只看最后两句话就能够明白个大概:

  1. 输入:输入为多个字符串的集合,中间用空格分割

  2. 输出:输出为同样长度的字符串,空格位置保持不变;单个单词中,字符发生了逆置;并且有趣的是,大写的位置没有发生改变,也就是说,指定的位置上的字符大写。

为了实现这道题,我进行了以下的思考。

二、问题解决:std::regex 和 std::reverse

这道题的思路其实非常简单:

  1. 首先,分割字符串,得到单词的集合

  2. 然后,将每个单词中的字符逆置

第一步考虑使用正则库分割(方便),第二步考虑使用自带的逆置函数:

class Solution {
public:
    string wordRverse(string s) {
        vector<bool> caps;
        for (auto c : s)
            caps.push_back(isupper(c) ? true : false);
        reverse(s.begin(), s.end());
        for (int i = 0; i < s.size(); ++i)
            if (caps[i]) s[i] = toupper(s[i]);
            else s[i] = tolower(s[i]);
        return s;
    }

    string reverseString(string s) {
        regex e(" ");
        smatch m;
        string result;
        while (regex_search(s, m, e)) {
            result += wordRverse(m.prefix().str());
            result += " ";
            s = m.suffix();
        }
        result += wordRverse(s);

        return result;
    }
};

代码逻辑还是比较简单的,这里不再赘述。

三、总结

这道题的解法一定有优化的地方。

另外,这道题用 python 肯定是更加简洁的,因为我记得 python 有一个非常方便的分割函数 T_T (C++11 自愧不如)。

这道题的正则的用法,还是值得学习的,确实也查了不少的资料。

另外,想要直接拿到可运行的代码的同学可以点击这里 wangying2016/ReverseString

算是一道比较有趣的问题吧。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值