首页 > 其他分享 >leetcode-541-easy

leetcode-541-easy

时间:2022-10-24 18:01:31浏览次数:87  
标签:begin end characters int 541 easy sb leetcode String

Reverse String II

Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.

If there are fewer 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 leave the other as original.

Example 1:

Input: s = "abcdefg", k = 2
Output: "bacdfeg"
Example 2:

Input: s = "abcd", k = 2
Output: "bacd"
Constraints:

1 <= s.length <= 104
s consists of only lowercase English letters.
1 <= k <= 104

思路一: 遍历每一个区间,区间内的字符做交换。用了 StringBuilder 来存储字符,发现耗时比用 char[] 多了好多

public String reverseStr(String s, int k) {
    StringBuilder sb = new StringBuilder(s);

    int i = 0;
    while (i < s.length()) {

        int begin = i;
        int end = Math.min(i + k - 1, s.length() - 1);

        while (begin < end) {
            char temp = sb.charAt(begin);
            sb.setCharAt(begin, sb.charAt(end));
            sb.setCharAt(end, temp);

            begin++;
            end--;
        }

        i += k*2;
    }

    return sb.toString();
}

标签:begin,end,characters,int,541,easy,sb,leetcode,String
From: https://www.cnblogs.com/iyiluo/p/16822295.html

相关文章

  • leetcode-504-easy
    Base7Givenanintegernum,returnastringofitsbase7representation.Example1:Input:num=100Output:"202"Example2:Input:num=-7Output:"-10......
  • 开发那些事儿:EasyCVR时间组件报错,是什么原因?
    EasyCVR具备较强的视频能力,可支持海量设备接入、汇聚与管理、视频监控、视频录像、云存储、回放与检索、智能告警、平台级联等功能。平台可支持多协议接入,包括:国标GB/T2818......
  • leetcode 2448
    首先需要这个结论.  而这里a_iai​为任意正整数,我们便可以直接将其**拆为**a_iai​个系数为11的绝对值表达式的和。接下来只需要考虑全体的中位数即可(采......
  • D1. Balance (Easy version)
    D1.Balance(Easyversion)Thisistheeasyversionoftheproblem.Theonlydifferenceisthatinthisversionthereareno"remove"queries.Initiallyyouha......
  • easyExcel 填充模板生成新的excel
    POM<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>3.1.1</version></dependency> 主要代......
  • leetcode 32. 最长有效括号 js实现
    https://leetcode.cn/problems/longest-valid-parentheses/给你一个只包含'(' 和')' 的字符串,找出最长有效(格式正确且连续)括号子串的长度。示例1:输入:s="(()"输出......
  • #yyds干货盘点# LeetCode 腾讯精选练习 50 题:合并两个有序链表
    题目:将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 示例1:输入:l1=[1,2,4],l2=[1,3,4]输出:[1,1,2,3,4,4]示例2:......
  • #yyds干货盘点# LeetCode 腾讯精选练习 50 题:最接近的三数之和
    题目:给你一个长度为n的整数数组 nums 和一个目标值 target。请你从nums中选出三个整数,使它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在恰好一......
  • Codeforces Round #830 C1. Sheikh(Easy version)
    题意给定一个长为\(n\)的非负整数序列\(\{a_n\}\),求\(l,r\)使\(f(l,r)=\text{sum}(l,r)-\text{xor}(l,r)\)最大,若答案不唯一,使\(r-l\)尽可能小,若仍不唯一,输出任意答案。......
  • 剑指 Offer 56 - I. 数组中数字出现的次数 - 力扣(LeetCode)
    剑指Offer56-I.数组中数字出现的次数-力扣(LeetCode)一个整型数组nums里除两个数字之外,其他数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复......