将指定字符串按照指定长度进行剪切的方法(我的代码库)


/// <summary>
        /// 将指定字符串按指定长度进行剪切
        /// </summary>
        /// <param name="oldStr">需要截断的字符串</param>
        /// <param name="maxLength">字符串的最大长度</param>
        /// <param name="endWith">超过长度的后缀</param>
        /// <returns>如果超过长度,返回截断后的新字符串加上后缀,否则,返回原字符串</returns>

        public static string StringTruncat(string oldStr, int maxLength, string endWith)
        {
            if (string.IsNullOrEmpty(oldStr))
            {
                return oldStr + endWith;
            }
            if (maxLength<1)
            {
                throw new Exception("返回的字符串长度必须大于[0]");
            }
            if (oldStr.Length>maxLength)
            {
                string strTmp = oldStr.Substring(0, maxLength);
                if (string.IsNullOrEmpty(endWith))
                {
                    return strTmp;
                }
                else
                {
                    return strTmp + endWith;
                }               
            }
            return oldStr;
        }

 

这是一个经典的动态规划问题,可以使用动态规划算法解决。时间复杂度为O(n^2)。 具体的实现过程如下: 1. 定义一个二维数组dp,其中dp[i][j]表示从第i个字符到第j个字符之间的子串是否是回文。 2. 初始化dp数组,将所有单个字符都视为回文,即dp[i][i]=true。 3. 从长度为2的子串开始,依次枚举所有可能的子串,更新dp数组。如果子串s[i]到s[j]是回文,则dp[i][j]=true,否则dp[i][j]=false。更新的过程如下: if(s[i]==s[j] && dp[i+1][j-1]) dp[i][j]=true; 4. 定义一个一维数组cut,其中cut[i]表示从第i个字符到末尾的子串最少需要切割的次数。 5. 初始化cut数组,将cut[i]初始值设为i到末尾的子串中最多可以切割的次数。 6. 从末尾开始,依次枚举所有可能的子串,更新cut数组。如果子串s[i]到s[j]是回文,则cut[i]=min(cut[i],cut[j+1]+1)。 7. 最终cut[0]即为所求答案。 以下是C++代码实现: ```cpp #include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; int minCut(string s) { int n = s.size(); vector<vector<bool>> dp(n, vector<bool>(n, false)); for (int i = 0; i < n; i++) { dp[i][i] = true; } for (int len = 2; len <= n; len++) { for (int i = 0; i < n - len + 1; i++) { int j = i + len - 1; if (s[i] == s[j] && (len == 2 || dp[i + 1][j - 1])) { dp[i][j] = true; } } } vector<int> cut(n, n); for (int i = n - 1; i >= 0; i--) { if (dp[i][n - 1]) { cut[i] = 0; } else { for (int j = i; j < n - 1; j++) { if (dp[i][j]) { cut[i] = min(cut[i], cut[j + 1] + 1); } } } } return cut[0]; } int main() { string s = "ababbbabbababa"; cout << "Minimum cuts needed: " << minCut(s) << endl; return 0; } ``` 这里我们使用了STL中的vector和string。其中vector用于存储dp数组和cut数组,string用于存储输入的字符串。最终输出需要的最小切割次数。 希望这个实现能满足你的需求!
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值