[Algorithm][综合训练][小葱的01串][小红的ABC][不相邻取数]详细讲解

时间:2025-04-25 07:43:19
  • 自己的版本:动态规划
    #include <iostream>
    #include <string>
    #include <vector>
    using namespace std;
    
    int main()
    {
        string str;
        cin >> str;
    
        int n = str.size();
        vector<vector<bool>> dp(n, vector<bool>(n, false));
    
        int minLen = 101;
        for(int i = n - 1; i >= 0; i--)
        {
            for(int j = i; j < n; j++)
            {
                if(str[i] == str[j])
                {
                    dp[i][j] = i + 1 < j ? dp[i + 1][j - 1] : true;
    
                    int len = j - i + 1;
                    if(dp[i][j] && len < minLen && len > 1)
                    {
                        minLen = len;
                    }
                }
            }
        }
    
        cout << (minLen == 101 ? -1 : minLen )<< endl;
    
        return 0;
    }
    
  • 优化版本:找规律 --> 仅需判断长度为2以及长度为3的子串是否是回文串即可
    #include <iostream>
    #include <string>
    using namespace std;
    
    int main()
    {
    	string str;
    	cin >> str;
    	int n = str.size();
    
    	int ret = -1;
    	for(int i = 0; i < n; i++)
    	{
    		if(i + 1 < n && str[i] == str[i + 1]) // 判断⻓度为2的⼦串
    		{
    			ret = 2;
    			break;
    		}
    
    		if(i + 2 < n && str[i] == str[i + 2]) // 判断⻓度为 3 的⼦串
    		{
    			ret = 3;
    		}
    	}
    
    	cout << ret << endl;
    
    	return 0;
    }