[leetcode] Palindrome Partitioning

本文详细介绍了如何通过递归算法解决LeetCode中的回文拆分问题,包括代码实现、核心思路及优化技巧。

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

From : https://leetcode.com/problems/palindrome-partitioning/

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

For example, given s = "aab",
Return

  [
    ["aa","b"],
    ["a","a","b"]
  ]
class Solution {
public:
    vector<vector<string>> partition(string s) {
        vector<vector<string>> ans;
        if(s == "") return ans;
        vector<string> cur;
        find(ans, cur, s, 0, s.size()-1);
		return ans;
    }
    void find(vector<vector<string>>& ans, vector<string>& cur, string s, int start, int end) {
        if(start > end) {ans.push_back(cur); return; }
        for(int i=start; i<=end; i++) {
            if(isPalindrome(s, start, i)) {
				cur.push_back(s.substr(start, i-start+1));
                find(ans, cur, s, i+1, end);
				cur.pop_back();
            }
        }
    }
    bool isPalindrome(string s, int start, int end) {
        while(start < end) {
            if(s[start] != s[end]) return false;
            start++;
            end--;
        }
        return true;
    }
};

public class Solution {
    public List<List<String>> partition(String s) {
		List<List<String>> ans = new ArrayList<List<String>>();
		if (s != null && !"".equals(s)) {
			find(s, 0, s.length() - 1, new LinkedList<String>(), ans);
		}
		return ans;
	}

	private void find(String s, int st, int ed, LinkedList<String> fd, List<List<String>> ans) {
		if (st > ed) {
			ans.add(new ArrayList<String>(fd));
			return;
		}
		for (int i = st; i <= ed; ++i) {
			if (valid(s, st, i)) {
			    String me = s.substring(st, i + 1);
				fd.add(me);
				find(s, i + 1, ed, fd, ans);
				fd.removeLast();
			}
		}
	}

	private boolean valid(String s, int i, int j) {
		while (i < j) {
			if (s.charAt(i++) != s.charAt(j--)) {
				return false;
			}
		}
		return true;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值