C++


  • 0
    J
    class Solution {
    public:
        string reverseStr(string s, int k) {
            int i = 0,j=0;
            int count =0;
            while(j<s.size())
            {
                count = 0;
                while(j<s.size() && count<2*k){j++;count++;}
                if(count<k)reverse(s,i,j-1);
                if(count>=k && count<=2*k) reverse(s,i,i+k-1);//注意长度要减1.
                i = j;
            }
            return s;
        }
        void reverse(string&s,int start,int end) // 要加&。
        {
            while(start<end)
            {
                swap(s[start],s[end]);
                start++;
                end--;
            }
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.