Wednesday, February 5, 2014

An in-place algorithm for String Transformation

http://www.geeksforgeeks.org/an-in-place-algorithm-for-string-transformation/



static String stringTransformation(String str)
{
int n = str.length();
if(n == 0 || n == 1 || n == 2) return str;
char a[] = str.toCharArray();
int i,front = 2, rear, j;
for(i = 1; i < n && front {

rear = i;
j = front;
char tmp = a[j];
while (rear {
a[j] = a[j-1];
j--;
}
a[rear] = tmp;
front = front+2;
}

return new String(a);
}


Exercise: 
Given string in the form “abcdefg1234567″, convert it to “a1b2c3d4e5f6g7″ in-place and in O(n) time complexity.

No comments:

Post a Comment