help on code improvement and time effiency
I wrote a program that reverses each word in a string. For example hello and goodbye is turned into olleh dna eybdoog. My program works, however the time efficiency is o(n^2) and I probably could of written less code. I am trying not to use any of the string.functions() ( I used string.length() once). Any tips or suggestions would be appreciated.
#include <iostream>
using namespace std;
void breakString(string& me, char * otherOne, int len, int count);
void reverseString(char* s);
int main () {
string me=("hello and goodbye");
char * otherOne;
int len=0;
int count=0;
for (len; len<me.length()+1; len++){
count++;
if (me[len]=='\0') {
otherOne=new char[count];
len-=count-1;
count=0;
for (len; me[len]; len++){
otherOne[count]=me[len];
count++;
}
reverseString(otherOne);
breakString( me, otherOne, len, count);
}
if (me[len]==' ' ) {
otherOne=new char[count];
len-=count-1;
count=0;
for (len; me[len] != ' '; len++){
otherOne[count]=me[len];
count++;
}
reverseString(otherOne);
breakString( me, otherOne, len, count);
count=0;
otherOne=NULL;
delete[]otherOne;
}
}
delete[]otherOne;
cout << me;
return 0;
}
void reverseString(c开发者_如何学Pythonhar* s)
{
int len =0;
char swap;
for (len=0; s[len] != '\0'; len++);
for ( int i=0; i<len/2; i++)
{
swap = *(s+i);
*(s+i)= *(s+len-i-1);
*(s+len-i-1) = swap;
}
}
void breakString(string &me, char * otherOne, int len, int count){
len-=count;
for (count=0; otherOne[count]; count++){
me[len]=otherOne[count];
len++;
}
}
Isn't far simple something like
#include <iostream>
using namespace std;
int main () {
string me=("hello and goodbye");
int i,j, index=0;
char tmp;
for (i=0; i<me.length()+1; i++)
if (me[i] == ' ' || me[i] == '\0') {
for(j=i-1;j>index;j--,index++) {
tmp = me[index];
me[index] = me[j];
me[j] =tmp;
}
index = i+1;
}
cout << me;
return 0;
}
?
Complexity is O(n): each word is read twice (or, better, one and a half times): once since the program finds a space or a \0, then, in the nested for, the word is reversed. index
indicates the word starting char.
You should be able to do this with a stack in between your input and output strings. The stack's useful to hold the current word, and it does the reversing for you, too. I'm not going to write the full code for it, but the algorithm is:
String output = ""
char Stack stack = []
while input.not_empty:
char c = input.get_char
if c == ' ':
while stack.not_empty:
output.put_char(stack.pop)
output.put_char(c)
else:
stack.push(c)
while stack.not_empty:
output.put_char(stack.pop)
return output
That'll give you O(n), and it's pretty easy to prove:
- Each character is read once (O(1))
- It's pushed onto the stack (at most) once (O(1))
- It's popped off the stack at most once (O(1))
- It's written once (O(1))
So: 4 * n * O(1), which is O(n).
Hope this helps!
PS: If this is homework, people are more likely to help you if you tag it as such.
精彩评论