rocksc30 / LeetCode

用于力扣刷题打卡
2 stars 0 forks source link

541. 反转字符串 II #18

Open rocksc30 opened 1 year ago

rocksc30 commented 1 year ago
class Solution {
    public String reverseStr(String s, int k) {
        char[] arry = s.toCharArray();
        int n = arry.length;

        int i = 0;
        for(; i < n; i += 2 * k){
            int b = i + k;
            reverseA2B(arry, i, b > n ? n : b);
        }
        return new String(arry);
    }

    public void reverseA2B(char[] s, int a, int b){
        char tmp;
        for(int i = a; i < (b+a)/2; i++){
            tmp = s[i];
            s[i] = s[b - i - 1 + a];
            s[b - i - 1 + a] = tmp;
        }
    }
}
Ni-Guvara commented 1 year ago
//  使用库函数进行交换
class Solution {
public:
    string reverseStr(string s, int k) {

            int len = s.length();

            for(int index  =  0 ; index < len ; index += 2 * k)
            {
                int n = 0;

                auto begin = s.begin();
                auto end = s.begin();

                if(index + k  > len )
                    n = len ;
                else
                    n = index + k;

                std::advance(begin,index);
                std::advance(end, n );
                std::reverse(begin,end);

            }
            return s;
    }
};