Palindrome Permutation I/II

要点:

  • oddCount to increase/decrease count
  • II:
    • chars: 先统计,再得到一半的c,相同的在一起,所以是不用排序的(permute去重需要排序)
    • odds: odds只能在中间,所以要存起来,最后直接拼接,不参与permutation。这样就免去了用变量计数来做奇偶判定。

https://repl.it/ChGE/1 (I: java)

错误点:

  • java: string foreach loop: for(char c : s.toCharArray()) else : error: for-each not applicable to expression type
  • java: == higher priority than & : (umap.get(c)&1)==1

https://repl.it/ChGE/2 (I: python)

https://repl.it/Chza/2 (II: python)

错误点:

  • permutation 1:注意和combination不同,recursion里的index是position(一律用start省的出错),而循环是对每个字符,进入下一层passed in是start+1
  • 如果+和if else,注意括号
import java.util.*;

class Main {
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.canPermutePalindrome("code"));
System.out.println(sol.canPermutePalindrome("aab"));
System.out.println(sol.canPermutePalindrome("carerac"));
}
} /*
Given a string, determine if a permutation of the string could form a palindrome.
For example,
"code" -> False, "aab" -> True, "carerac" -> True.
Hint:
Consider the palindromes of odd vs even length. What difference do you notice?
Count the frequency of each character.
If each character occurs even number of times, then it must be a palindrome. How about character which occurs odd number of times?
Tags: Hash Table
Similar Problems: (M) Longest Palindromic Substring, (E) Valid Anagram, (M) Palindrome Permutation II
*/ class Solution {
public boolean canPermutePalindrome(String s) {
Map<Character, Integer> umap = new HashMap<>();
int oddCount = 0; for(char c : s.toCharArray()) { // error 1: error: for-each not applicable to expression type for(char c: s)
if(!umap.containsKey(c)) {
umap.put(c, 0);
}
umap.put(c, umap.get(c)+1);
if((umap.get(c)&1)==1){ // error 2: error: bad operand types for binary operator '&' int and boolean: == has higher priority than &
oddCount++;
} else {
oddCount--;
}
}
return oddCount<=1;
}
}
import java.util.*;

class Main {
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.canPermutePalindrome("code"));
System.out.println(sol.canPermutePalindrome("aab"));
System.out.println(sol.canPermutePalindrome("carerac"));
}
} /*
Given a string, determine if a permutation of the string could form a palindrome.
For example,
"code" -> False, "aab" -> True, "carerac" -> True.
Hint:
Consider the palindromes of odd vs even length. What difference do you notice?
Count the frequency of each character.
If each character occurs even number of times, then it must be a palindrome. How about character which occurs odd number of times?
Tags: Hash Table
Similar Problems: (M) Longest Palindromic Substring, (E) Valid Anagram, (M) Palindrome Permutation II
*/ class Solution {
public boolean canPermutePalindrome(String s) {
Map<Character, Integer> umap = new HashMap<>();
int oddChars = 0; for(char c : s.toCharArray()) { // error 1: error: for-each not applicable to expression type for(char c: s)
if(!umap.containsKey(c)) {
umap.put(c, 0);
}
umap.put(c, umap.get(c)+1);
if((umap.get(c)&1)==1){ // error 2: error: bad operand types for binary operator '&' int and boolean: == has higher priority than &
oddChars++;
} else {
oddChars--;
}
}
return oddChars<=1;
}
}
# Problem Description:

# 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 [].

# Hint:

# If a palindromic permutation exists, we just need to generate the first half of the string.
# To generate all distinct permutations of a (half of) string, use a similar approach from: Permutations II or Next Permutation. from collections import Counter class Solution(object):
def generatePalindromes(self, s):
"""
:type s: str
:rtype: List[str]
"""
def permute(s, start, used, res, solutions):
if start>=len(s):
solutions.append(res)
return for i in xrange(len(s)): # error, not from start
if i>start and s[i]==s[i-1] and not used[i-1]: continue
if not used[i]:
used[i]=True
permute(s, start+1, used, res+s[i], solutions)
used[i]=False counts, chars = Counter(s), []
odds, evens = [], []
for c in counts:
if counts[c]%2:
odds.append(c)
if counts[c]>1: # error: odds can also append
chars.append(c*(counts[c]/2))
else:
evens.append(c)
chars.append(c*(counts[c]/2)) if len(odds)>1:
return []
# print chars
used, solutions = [False]*len(chars), []
permute(chars, 0, used, "", solutions)
# print solutions return [s+(odds[0] if odds else "")+s[::-1] for s in solutions] # error: priority sol = Solution()
assert sol.generatePalindromes("aabb")==['abba', 'baab']
assert sol.generatePalindromes("abc")==[]
assert sol.generatePalindromes("aaabb")==['ababa', 'baaab']

最新文章

  1. python3.5 正则表达式
  2. git 设置 key 到服务器,同步代码不需要输入用户名和密码
  3. 使用recon/domains-hosts/baidu_site模块,枚举baidu网站的子域
  4. IOS彩票第三天界面
  5. 【node.js】安装express后,&#39;express&#39; 不是内部或外部命令的问题
  6. eWebeditor编辑器上传图片路径错误解决方法[疑难杂症]【转,作者:unvs】
  7. ES mlockall作用——preventing that memory from being paged to the swap area
  8. Codeforces Round #150 (Div. 2)
  9. Arduino uno R3 ISP刷Rootloader for arduino pro mini
  10. 在linux下查看内核版本、gcc版本、操作系统多少位等参数
  11. [译]GC专家系列1: 理解Java垃圾回收
  12. 判断ios是app第一次启动
  13. java --- 对象的创建过程
  14. margin外边距合并问题以及解决方式
  15. 给GRUB添加新的项目
  16. Linux学习笔记:scp远程拷贝文件
  17. 内存对齐与ANSI C中struct型数据的内存布局 【转】
  18. Java 希尔排序
  19. SpringBoot使用端口运行
  20. ios开发之 -- stringByAddingPercentEscapesUsingEncoding方法被替换 iOS9.0

热门文章

  1. 第二章--Win32程序运行原理 (部分概念及代码讲解)
  2. php生成静态文件
  3. 通过一个小问题来学习SQL关联查询
  4. DWR的Reverse Ajax技术实现
  5. Mysql进阶(二)
  6. 【GOF23设计模式】命令模式
  7. windows下mongodb安装与使用
  8. CSS3选择器(一)
  9. thinkPHP学习笔记(1)
  10. SharePoint 2013开发环境准备一些小事项