前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >541.Reverse String II(String-Easy)

541.Reverse String II(String-Easy)

作者头像
Jack_Cui
发布2018-01-08 16:09:54
4430
发布2018-01-08 16:09:54
举报
文章被收录于专栏:Jack-CuiJack-Cui

Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.

Example:

Input: s = “abcdefg”, k = 2 Output: “bacdfeg”

Restrictions:

  • The string consists of lower English letters only.
  • Length of the given string and k will in the range [1, 10000]

题目:根据k,反转字符串。

代码语言:javascript
复制
    /**
     * 0            k           2k          3k
     * |-----------|-----------|-----------|---
     * +--reverse--+           +--reverse--+
     */

每2k个字符,反转前面的k个字符。如果少于k个字符,反转所有字符。如果大于等于k个字符小于2k个字符,那么反转前面的k个字符,剩余的字符保留不动。

思路:使用reverse函数进行反转。代码依旧很简单。

Language : cpp

代码语言:javascript
复制
class Solution {
public:
    string reverseStr(string s, int k) {
        for(int i = 0; i < s.size(); i += 2*k){
            reverse(s.begin()+i, min(s.begin()+i+k, s.end()));
        }
        return s;
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-04-28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档