LeetCode题解–131. Palindrome Partitioning
来源:互联网 发布:文字翻译语音软件 编辑:程序博客网 时间:2024/05/19 16:48
链接
LeetCode题目:https://leetcode.com/problems/palindrome-partitioning/
难度:Medium
题目
Given a string s, partition s such that every substring of the partition is a palindrome.
题目大意是给定一个字符串,返回所有子串是回文串的划分情况。比如s=”aab”,返回[ [“aa”,”b”], [“a”,”a”,”b”]]。
分析
使用dfs算法搜索划分点,当出现目前子串不是回文串时可以停止继续向下搜索。
代码
class Solution {public: vector<vector<string>> partition(string s) { if (s == "") ans.push_back({""}); else { s_len = s.length(); ss = s; vector<int> cut_point; dfs(0, cut_point); } return ans; } bool isPalindrome(string str) { int str_len = str.size(); for (int i = 0; i < str_len / 2; i++) { if (str[i] != str[str_len - 1 - i]) return false; } return true; } void dfs(int n, vector<int> cut_point) { int cut_len = (int) cut_point.size(); if (cut_len) { int left_pos = cut_point[cut_len - 1]; string cut_str = ss.substr(left_pos, n - left_pos); if (!isPalindrome(cut_str)) return; } cut_point.push_back(n); if (n == s_len) { vector<string> temp; for (int i = 0; i < cut_point.size() - 1; i++) { temp.push_back(ss.substr(cut_point[i], cut_point[i + 1] - cut_point[i])); } ans.push_back(temp); return; } else { for (int i = n + 1; i <= s_len; i++) { dfs(i, cut_point); } } }private: vector<vector<string>> ans; int s_len; string ss;};
0 0
- LeetCode题解–131. Palindrome Partitioning
- LeetCode题解:Palindrome Partitioning
- Palindrome Partitioning II|leetcode题解
- LeetCode - Palindrome Partitioning II 题解
- LeetCode 131. Palindrome Partitioning
- [LeetCode]131.Palindrome Partitioning
- [Leetcode] 131. Palindrome Partitioning
- [leetcode] 131.Palindrome Partitioning
- [LeetCode]131. Palindrome Partitioning
- 131. Palindrome Partitioning LeetCode
- Leetcode 131. Palindrome Partitioning
- LeetCode 131. Palindrome Partitioning
- LeetCode *** 131. Palindrome Partitioning
- LeetCode 131. Palindrome Partitioning
- LeetCode-131.Palindrome Partitioning
- 【leetcode】131. Palindrome Partitioning
- [leetcode] 131. Palindrome Partitioning
- 【Leetcode】131. Palindrome Partitioning
- fastJson 详解
- java中this关键字的作用
- Oracle数据库服务器CPU持续100%之等待事件asynch descriptor resize
- Redis相关参数设置总结
- TCP/IP
- LeetCode题解–131. Palindrome Partitioning
- Web Api 的 路由机制
- 百度地图
- Caffe学习笔记—Caffe模型
- Github上的项目描述添加图片
- kali2.0更新源启用中文输入法
- vr
- python super()
- 任意版本MATLAB安装C2000支持包