Leetcode 132 Palindrome Partitioning II(BFS)

本文介绍了解决LeetCode上的132题(Palindrome Partitioning II)的方法,采用BFS策略来寻找最少的分割次数使字符串成为回文串。通过判断子字符串是否为回文来推进搜索过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目连接:Leetcode 132 Palindrome Partitioning II

解题思路:每次向后枚举若干字符,判断这些字符组成的字符串是否为回文串。因为要求最小切割数,所以用BFS,记录当前切割到的位置。

class Solution {
	public:
		bool isPalindrome(string s) {
			int n = s.size();
			for (int i = 0; i + i < n; i++)
				if (s[i] != s[n-i-1]) return false;
			return true;
		}

		int minCut(string s) {
			if (s.size() == 0) return 0;

			queue<pair<int, int>> que;
			que.push(make_pair(0, 0));

			int ans, n = s.size();
			bool* flag = new bool[n+1];
			for (int i = 0; i <= n; i++) flag[i] = false;

			while (!que.empty()) {
				int start = que.front().first;
				int step = que.front().second;
				que.pop();

				if (start >= n) {
					ans = step - 1;
					break;
				}

				for (int i = start; i < n; i++) {
					if (flag[i+1]) continue;

					string tmp = s.substr(start, i - start + 1);
					if (isPalindrome(tmp)) {
						flag[i+1] = true;
						que.push(make_pair(i+1, step + 1));
					}
				}
			}

			delete[] flag;
			return ans;
		}
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值