Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update 01.04.md #410

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 34 additions & 29 deletions ebook/zh/01.04.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,28 @@
代码如下::

```cpp
#include <stdbool.h>

bool IsPalindrome(const char *s, int n)
{
//非法输入
if (s == NULL || n < 1)
return false;
char *front, *back;

//初始化头指针和尾指针
front = s;
back = s + n - 1;

while (front < back)
{
if (*front != *back)
return false; // 不是回文,立即返回
++front;
--back;
}
return true; // 是回文
//非法输入
if (s == NULL || n < 1)
return false;

const char *front, *back;

//初始化头指针和尾指针
front = s;
back = s + n - 1;

while (front < back)
{
if (*front != *back)
return false; // 不是回文,立即返回
++front;
--back;
}
return true; // 是回文
}
```

Expand All @@ -48,20 +51,22 @@ bool IsPalindrome(const char *s, int n)
上述解法一从两头向中间扫描,那么是否还有其它办法呢?我们可以先从中间开始、然后向两边扩展查看字符是否相等。参考代码如下:

```cpp
#include <stdbool.h>
bool IsPalindrome2(const char *s, int n)
{
if (s == NULL || n < 1)
return false; // 非法输入
char *first, *second;

int m = ((n >> 1) - 1) >= 0 ? (n >> 1) - 1 : 0; // m is themiddle point of s
first = s + m;
second = s + n - 1 - m;

while (first >= s)
if (s[first--] != s[second++])
return false; // not equal, so it's not apalindrome
return true; // check over, it's a palindrome
if (s == NULL || n < 1)
return false; // 非法输入

const char *first, *second;

int m = ((n >> 1) - 1) >= 0 ? (n >> 1) - 1 : 0; // m 是中间点
first = s + m;
second = s + n - 1 - m;

while (first >= s)
if (*(first--) != *(second++))
return false; // 不是回文,立即返回
return true; // 是回文
}
```
时间复杂度:O(n),空间复杂度:O(1)。
Expand Down