C language classic algorithm - string reversed

xiaoxiao2021-03-14  197

Classic algorithm - string reversed

Under the optimum state, the string is reversed (inversion of the string)

2005-11-18 10:18:35

From: http://www.exuesoft.com/Article/view.aspx? NewsiD = 116

Void Reverse (Char S [])

{

For (int i = 0, j = strlen (s) -1; i

{

CHAR C = S [I];

S [i] = s [j];

S [J] = C;

}

}

This function is the second edition of classic works in Kernighan and Ritchie collaboration.

Comment: This algorithm should be optimal whether it is from time complexity or from the smallest space.

Time only uses half of the traversal string length, just create a string length

Half of space. Of course, we can also further reduce it from space.

Void Reverse (Char S [])

{

Char C;

For (int i = 0, j = strlen (s) -1; i

{

C = s [i];

S [i] = s [j];

S [J] = C;

}

}

We declare C from the outside, so we only use a variable during the entire string reverse. Spatial use

Little! But what we have to consider is that when we pass the string, only one character is used,

The above algorithm is not as efficient as the first algorithm, because the above function is created, and it has created an unused

CHAR object, and C language recommendation: "The variable declaration" is delayed as possible. " So really I still agree with "TCPL"

The method of the upper place, in the form of defined CHAR C = S [i]!

转载请注明原文地址:https://www.9cbs.com/read-129305.html

New Post(0)