2016校招編程題

      給定一個字符串.問是否可以通過添加一個字符將其變成迴文串。


輸入:一行由小寫字母構成的字符串,長度不超過10。

輸出:YES 或者NO


輸入樣例:testest

輸出樣例:YES


<span style="font-size:18px;">#include <iostream>
#include <string>

using namespace std;

bool fun(string str)
{
    if (str.length() == 0) return true;
    
    bool result = false;
    
    int low = 0;
    int high = str.length() - 1;
    
    while (low < high && str[low] == str[high]) {
        low++;
        high--;
    }
    
    if (high <= low) {
        result = true;
    } else
    {
        if (high == low + 1) {
            result = true;
        } else
        {
            int temp_low = low;
            int temp_high = high - 1;
            
            while (temp_low < temp_high && str[temp_low] == str[temp_high]) {
                temp_low++;
                temp_high--;
            }
            
            if (temp_low >= temp_high) {
                result = true;
            } else
            {
                temp_low = low + 1;
                temp_high = high;
                
                while (temp_low < temp_high && str[temp_low] == str[temp_high]) {
                    temp_low++;
                    temp_high--;
                }
                
                if (temp_low >= temp_high) {
                    result = true;
                } else
                {
                    result = false;
                }
            }
        }
    }
    
    return result;
}

int main(int argc, const char * argv[]) {
    // insert code here...
    
    string str;
    
    cin >> str;
    
    bool result = fun(str);
    
    if (result) {
        cout << "Yes" << endl;
    } else
    {
        cout << "No" << endl;
    }
    
    return 0;
</span>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章