A simple C solution [Accepted]


  • 0
    B
    char* reverseStr(char* s, int k) {
        if(s==NULL||k<2)
        {return s;}
        int len=strlen(s);
        int j=0,temp=0;
        bool flag=false;
        for(j=0;j<len;j=j+k)
        {
            flag=!flag;
            if(flag&&j+k<=len)
            {
                temp=k+j-1;
                for(int i=j;i<j+k/2;i++)
                {
                    s[i]=s[i]^s[temp];
                    s[temp]=s[i]^s[temp];
                    s[i]=s[temp]^s[i];
                    temp--;
                }
            }else if(flag&&j+k>len)
            {
                temp=len-1;
                for(int i=j;i<j+(len-j)/2;i++)
                {
                    s[i]=s[i]^s[temp];
                    s[temp]=s[i]^s[temp];
                    s[i]=s[temp]^s[i];
                    temp--;
                }
                return s;
            }
        }
        return s;  
    }
    

Log in to reply
 

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