The answer is of course, yes. This is a trick so important that it becomes one of the frequently asked interview questions. An in-depth discussion is in Programming Pearls, one of the must-read book in Computer Science.
The trick is to do three reverse operation. One for the entire string, one from index 0 to k-1, and lastly index k to n-1. Magically, this will yield the correct rotated array, without any extra space! (Of course, you need a temporary variable for swapping).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
void
reverse_string
(
char
*
str
,
int
left
,
int
right
)
{
char
*
p1
=
str
+
left
;
char
*
p2
=
str
+
right
;
while
(
p1
<
p2
)
{
char
temp
=
*
p1
;
*
p1
=
*
p2
;
*
p2
=
temp
;
p1
++
;
p2
--
;
}
}
void
rotate
(
char
*
str
,
int
k
)
{
int
n
=
strlen
(
str
)
;
reverse_string
(
str
,
0
,
n
-
1
)
;
reverse_string
(
str
,
0
,
k
-
1
)
;
reverse_string
(
str
,
k
,
n
-
1
)
;
}
|