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)的空间复杂度。但是第二种从中间往两边判断的方法在解决一些问题时有独到之处。

  • 相关阅读:
    字典_序列解包用于列表元组字典
    字典_序列解包用于列表元组字典
    字典_元素的访问_键的访问_值的访问_键值对的访问
    字典_特点_4种创建方式_普通-dict
    元组_生成器推导式创建元组-总结
    MySql高级
    技术点
    全文检索ElasticSearch
    数仓管理
    SpringCache
  • 原文地址:https://www.cnblogs.com/friend-A/p/9911632.html
Copyright © 2011-2022 走看看