zoukankan      html  css  js  c++  java
  • 回文串之判断

     1 //从左右两边开始比较判断
     2 #include<iostream>
     3 #include<string.h>
     4 using namespace std;
     5 const int MAXN = 1e5;
     6 bool is_palindrome(char *s, int len)
     7 {
     8     if(s == NULL || len < 1)    //非法输入
     9         return false;
    10     char *front, *tail;    //首尾指针
    11     //指针声明了就要记得初始化
    12     front = s;
    13     tail = s + len - 1;
    14     while(front < tail)
    15     {
    16         if(*front != *tail)
    17             return false;
    18         front++;
    19         tail--;
    20     }
    21     return true;
    22 }
    23 int main()
    24 {
    25     char str[MAXN];
    26     while(cin >> str)
    27     {
    28         int len = strlen(str);
    29         cout << is_palindrome(str, len) << endl;
    30     }
    31     return 0;
    32 }
    33 //时间复杂度O(n),空间复杂度O(1)
     1 //从中间开始往两边判断
     2 #include<iostream>
     3 #include<string.h>
     4 using namespace std;
     5 const int MAXN = 1e5;
     6 bool is_palindrome(char *s, int len)
     7 {
     8     if(s == NULL || len < 1)
     9         return false;
    10     char *left, *right;
    11     int mid = ((len >> 1) - 1) >= 0 ? (len >> 1) - 1 : 0;
    12     left = s + mid;
    13     right = s + len - 1 - mid;
    14     while(left >= s)
    15     {
    16         if(*left != *right)
    17             return false;
    18         left--;
    19         right++;
    20     }
    21     return true;
    22 }
    23 int main()
    24 {
    25     char str[MAXN];
    26     while(cin >> str)
    27     {
    28         int len = strlen(str);
    29         cout << is_palindrome(str, len) << endl;
    30     }
    31     return 0;
    32 }
    33 //时间复杂度O(n),空间复杂度O(1)

    上面两种判断回文的方法在复杂度上没有区别,都是O(n)的时间复杂度和O(1)的空间复杂度。但是第二种从中间往两边判断的方法在解决一些问题时有独到之处。

  • 相关阅读:
    GUI 之 JDialog弹窗
    GUI Swing 之 JFrame窗体
    GUI 键盘监听事件
    GUI 窗口监听事件
    GUI 鼠标监听事件,模拟画图工具
    shell编程
    Ubuntu20.04 Linux初识
    rlwrap的使用
    5个相见恨晚的Linux命令,每一个都非常实用
    Bash初识与常用命令
  • 原文地址:https://www.cnblogs.com/friend-A/p/9911632.html
Copyright © 2011-2022 走看看