Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Palindrome Permutation II

Posted on February 19, 2018July 26, 2020 by braindenny

Palindrome Permutation II



Similar Problems:

  • Letter Case Permutation
  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #combination

Given a string s, return all the palindromic permutations (without duplicates) of it. Return an empty list if no palindromic permutation could be form.

For example:

Given s = "aabb", return ["abba", "baab"].

Given s = "abc", return [].

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


## https://code.dennyzhang.com/palindrome-permutation-ii
// Basic Ideas: permutation without duplicates
//
// Complexity: Time ? Space ?
func dfs(combination string, length int, m map[rune]int, central string, res *[]string) {
    if len(combination) == length {
        str := combination + central
        for i:=len(combination)-1; i>=0; i-- {
            str += string(combination[i])
        }
        *res = append(*res, str)
        return
    }

    for i:=0; i<256; i++ {
        ch := rune(i)
        if m[ch] > 0 {
            m[ch]--
            dfs(combination+string(ch), length, m, central, res)
            m[ch]++
        }
    }
}

func generatePalindromes(s string) []string {
    m := map[rune]int{}
    for _, ch := range s { m[ch]++ }
    central := ""
    length := 0
    for key, val := range m {
        if val%2 != 0 { 
            if central != "" {
                return []string{}
            }
            central = string(key)
        }
        m[key] = val/2
        length += m[key]
    }
    res := []string{}
    dfs("", length, m, central, &res)
    return res
}
linkedin
github
slack

Post Views: 5
Posted in MediumTagged #backtracking, #codetemplate, #combination

Post navigation

LeetCode: Generalized Abbreviation
LeetCode: Sequence Reconstruction

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.