美文网首页
stack判断回文字串

stack判断回文字串

作者: 壹顾倾城 | 来源:发表于2020-12-15 17:28 被阅读0次
/********************************
 * 程序名称:判断回文字串 
 * 程序来源:B站 Tracy老师视频 https://www.bilibili.com/video/BV1Uk4y1r7mr
 * 功能实现:输入字符串,判断回文 
 * 开发时间:2020 -12- 15
 *******************************/

#include <iostream>
#include <stack>

using namespace std;
stack<char> st;   //字符串堆栈 
//ishw(string s)
bool ishw(string s) {
    int len, mid, next; //len-串长度
    len = s.size();         //len-字符串长度  
    mid = len / 2;
    while(!st.empty()) {
        st.pop();           //清空堆栈 
    } 
    
    if(len % 2 == 0) {      //获取子串的中间位置
        next = mid;      //mid-字符中间位置
    } else {
        next = mid + 1; 
    }
    //将前半部分子串加入堆栈 
    for(int i=0; i<mid; i++) {
        st.push(s[i]);     
    }
    //堆栈前半部分字符和后半部分比较,相同出栈 
    for(int i=mid; i<len; i++) {
        if(s[i] == st.top()) {
            st.pop();        //出栈 
        }
    }
    //栈空,是回文 
    if(st.empty()== true) {
        return true;
    } else {
        return false;   //不是回文 
    }       
}

//main() star
int main() {
    string s;       //输入字符串 
    cin >> s;
    if(ishw(s)) {   //判断回文 
        cout << "YES" << endl;
    } else {
        cout << "NO" << endl;
    }
    return 0; 
}

测试1:123321

123321
YES
--------------------------------
Process exited after 2.732 seconds with return value 0
请按任意键继续. . .

测试2:asdafafa

asdafafa
NO
--------------------------------
Process exited after 9.355 seconds with return value 0
请按任意键继续. . .

相关文章

网友评论

      本文标题:stack判断回文字串

      本文链接:https://www.haomeiwen.com/subject/xfvwgktx.html