s*****s 发帖数: 157 | 1 被问到的, 在 input1 中找 input2, 如果找到, 就从找到的位置返回剩余的input1.
问是否code是对的, 如何改进, 如何优化。
我觉得code是对的啊,
char* test( char* input1, const char* input2 )
{
while( *input1 )
{
char *a = input1, *b = input2;
while( (*a++ == *b++) && *a && *b );
if( *b == 0 )
return input1;
input1++;
}
return 0;
} | P*******b 发帖数: 1001 | 2 char -> const char
优化是不是把b放到a前面?
input1.
【在 s*****s 的大作中提到】 : 被问到的, 在 input1 中找 input2, 如果找到, 就从找到的位置返回剩余的input1. : 问是否code是对的, 如何改进, 如何优化。 : 我觉得code是对的啊, : char* test( char* input1, const char* input2 ) : { : while( *input1 ) : { : char *a = input1, *b = input2; : while( (*a++ == *b++) && *a && *b ); : if( *b == 0 )
| s*****s 发帖数: 157 | 3 其实code还是有错误, 比如
input1 is "abc", input2 is "b"
suppose to return "bc", but it returns "abc"
that "b++" is wrong... | s*****s 发帖数: 157 | | K******g 发帖数: 1870 | 5 这个是错误吗?我怎么觉得返回就是“bc”呢?
【在 s*****s 的大作中提到】 : 其实code还是有错误, 比如 : input1 is "abc", input2 is "b" : suppose to return "bc", but it returns "abc" : that "b++" is wrong...
| s*******t 发帖数: 248 | 6 input2 const char* -> char*
(*a++ == *b++) -> (*a == *b), then in the loop a++, b++.
then it will be fine.
input1.
【在 s*****s 的大作中提到】 : 被问到的, 在 input1 中找 input2, 如果找到, 就从找到的位置返回剩余的input1. : 问是否code是对的, 如何改进, 如何优化。 : 我觉得code是对的啊, : char* test( char* input1, const char* input2 ) : { : while( *input1 ) : { : char *a = input1, *b = input2; : while( (*a++ == *b++) && *a && *b ); : if( *b == 0 )
| s*****s 发帖数: 157 | 7 it is still wrong if you put 'a++, b++' inside the while(...){} loop
for example:
input1 is "abc"
input2 is ""
suppose to return null, it returns "abc" indeed. | s*****s 发帖数: 157 | 8 这个是错误, 返回不是 "bc", 你可以run 着试一下
【在 K******g 的大作中提到】 : 这个是错误吗?我怎么觉得返回就是“bc”呢?
| j***i 发帖数: 1278 | 9 一开始还要排除 空指针把,
input1 也应该是const pointer 毕竟也不休改input1
【在 s*******t 的大作中提到】 : input2 const char* -> char* : (*a++ == *b++) -> (*a == *b), then in the loop a++, b++. : then it will be fine. : : input1.
| s*****s 发帖数: 157 | 10 另外这个code是复杂度应该是 O(n^2), 不知道能不能改进 | s*****s 发帖数: 157 | 11 如果让input1也是const, 那么 char * func() 也要是 const 的, 因为program中有
return input1;
【在 j***i 的大作中提到】 : 一开始还要排除 空指针把, : input1 也应该是const pointer 毕竟也不休改input1
|
|