LeetCode 267. Palindrome Permutation II
原题链接在这里:https://leetcode.com/problems/palindrome-permutation-ii/
题目:
Given a string s
, return all the palindromic permutations (without duplicates) of it. Return an empty list if no palindromic permutation could be form.
Example 1:
"aabb"
["abba", "baab"]
Example 2:
"abc"
[]
题解:
先判断是否palindrome, 若不是返回空的res.
若是,先判断是否有一个奇数位,若有,改char放中间. 然后两边分别加.
Note: check to find single char after updating the map.
Don't forget to minus its count by 1 after appending it to item.
Time Complexity: O(2^n). n = s.length().
Space: O(n). stack space.
AC Java:
1 class Solution { 2 public List<String> generatePalindromes(String s) { 3 List<String> res = new ArrayList<>(); 4 if(s == null || s.length() == 0){ 5 return res; 6 } 7 8 int [] count = new int[256]; 9 int n = s.length(); 10 int po = -1; 11 for(int i = 0; i<n; i++){ 12 count[s.charAt(i)]++; 13 } 14 15 int oneCount = 0; 16 for(int i = 0; i<256; i++){ 17 oneCount += count[i]%2; 18 19 if(count[i]%2 == 1){ 20 po = i; 21 } 22 } 23 24 if(oneCount > 1){ 25 return res; 26 } 27 28 String init = ""; 29 if(po != -1){ 30 init += (char)po; 31 count[po]--; 32 } 33 34 dfs(count, init, n, res); 35 return res; 36 } 37 38 private void dfs(int [] count, String cur, int n, List<String> res){ 39 if(cur.length() == n){ 40 res.add(cur); 41 return; 42 } 43 44 for(int i = 0; i<count.length; i++){ 45 if(count[i] > 0){ 46 count[i] -= 2; 47 dfs(count, (char)i+cur+(char)i, n, res); 48 count[i] += 2; 49 } 50 } 51 } 52 }
标签:
LeetCode
, Backtracking
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· 编程神器Trae:当我用上后,才知道自己的创造力被低估了多少
· 开发的设计和重构,为开发效率服务
· 从零开始开发一个 MCP Server!
· Ai满嘴顺口溜,想考研?浪费我几个小时
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密