zoukankan      html  css  js  c++  java
  • 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:

    Input: "aabb"
    Output: ["abba", "baab"]

    Example 2:

    Input: "abc"
    Output: []

    题解:

    先判断是否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 }

    Palindrome Permutation相似. 

  • 相关阅读:
    MySQL 复制表结构和表数据
    学习使用Guava Retryer
    Maven 常用工具类整理
    转 全面理解Javascript闭包和闭包的几种写法及用途
    Python的全局变量
    python的内存管理机制
    Python 隔离沙箱 virtualenv
    <script> 的defer和async
    高性能Javascript(2) DOM编程
    高性能Javascript(1)
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/5265380.html
Copyright © 2011-2022 走看看