Skip to content

Instantly share code, notes, and snippets.

@luckypapa
Last active August 29, 2015 14:23
Show Gist options
  • Select an option

  • Save luckypapa/b9aad7f79e69adc76f5b to your computer and use it in GitHub Desktop.

Select an option

Save luckypapa/b9aad7f79e69adc76f5b to your computer and use it in GitHub Desktop.
No. 19 - Left Rotation of String
//http://codercareer.blogspot.kr/2011/11/no-19-left-rotation-of-string.html
// time complexity : O(n)
// space complexity : O(n)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void Reverse(char *pBegin, char *pEnd) {
if(pBegin == NULL || pEnd == NULL)
return;
while(pBegin < pEnd) {
char temp = *pBegin;
*pBegin = *pEnd;
*pEnd = temp;
pBegin ++, pEnd --;
}
}
char* leftRotationOfString(char *pStr, int n) {
/*
if (string == NULL)
return NULL;
int length = strlen(string);
char tempString[100];
char *rotationString = string;
//make string + string
strcpy(tempString, string);
strcat(tempString, string);
for (int i = index; i < length + index; i ++) {
*rotationString = tempString[i];
rotationString ++;
}
printf("rotation = %s \n", string);
return string;
*/
if(pStr != NULL) {
int nLength = strlen(pStr);
if(nLength > 0 && n > 0 && n < nLength) {
char* pFirstStart = pStr;
char* pFirstEnd = pStr + n - 1;
char* pSecondStart = pStr + n;
char* pSecondEnd = pStr + nLength - 1;
// Reverse the n leading characters
Reverse(pFirstStart, pFirstEnd);
// Reverse other characters
Reverse(pSecondStart, pSecondEnd);
// Reverse the whole string
Reverse(pFirstStart, pSecondEnd);
}
}
return pStr;
}
int main(void) {
printf("test start \n");
char *inputString = (char *)malloc(sizeof(char) * 50);
strcpy(inputString, "abcdef");
printf("input = %s, rotation = %s \n", inputString, leftRotationOfString(inputString, 1));
printf("input = %s, rotation = %s \n", inputString, leftRotationOfString(inputString, 2));
printf("input = %s, rotation = %s \n", inputString, leftRotationOfString(inputString, 3));
printf("input = %s, rotation = %s \n", inputString, leftRotationOfString(inputString, 4));
printf("input = %s, rotation = %s \n", inputString, leftRotationOfString(inputString, 5));
free(inputString);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment