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']

边工作边刷题:70天一遍leetcode: day 80的更多相关文章

  1. 边工作边刷题:70天一遍leetcode: day 89

    Word Break I/II 现在看都是小case题了,一遍过了.注意这题不是np complete,dp解的time complexity可以是O(n^2) or O(nm) (取决于inner ...

  2. 边工作边刷题:70天一遍leetcode: day 77

    Paint House I/II 要点:这题要区分房子编号i和颜色编号k:目标是某个颜色,所以min的list是上一个房子编号中所有其他颜色+当前颜色的cost https://repl.it/Chw ...

  3. 边工作边刷题:70天一遍leetcode: day 78

    Graph Valid Tree 要点:本身题不难,关键是这题涉及几道关联题目,要清楚之间的差别和关联才能解类似题:isTree就比isCycle多了检查连通性,所以这一系列题从结构上分以下三部分 g ...

  4. 边工作边刷题:70天一遍leetcode: day 85-3

    Zigzag Iterator 要点: 实际不是zigzag而是纵向访问 这题可以扩展到k个list,也可以扩展到只给iterator而不给list.结构上没什么区别,iterator的hasNext ...

  5. 边工作边刷题:70天一遍leetcode: day 101

    dp/recursion的方式和是不是game无关,和game本身的规则有关:flip game不累加值,只需要一个boolean就可以.coin in a line II是从一个方向上选取,所以1d ...

  6. 边工作边刷题:70天一遍leetcode: day 1

    (今日完成:Two Sum, Add Two Numbers, Longest Substring Without Repeating Characters, Median of Two Sorted ...

  7. 边工作边刷题:70天一遍leetcode: day 70

    Design Phone Directory 要点:坑爹的一题,扩展的话类似LRU,但是本题的accept解直接一个set搞定 https://repl.it/Cu0j # Design a Phon ...

  8. 边工作边刷题:70天一遍leetcode: day 71-3

    Two Sum I/II/III 要点:都是简单题,III就要注意如果value-num==num的情况,所以要count,并且count>1 https://repl.it/CrZG 错误点: ...

  9. 边工作边刷题:70天一遍leetcode: day 71-2

    One Edit Distance 要点:有两种解法要考虑:已知长度和未知长度(比如只给个iterator) 已知长度:最好不要用if/else在最外面分情况,而是loop在外,用err记录misma ...

随机推荐

  1. [.NET] 使用C#开发SQL Function来提供数据 - 天气预报

    [.NET] 使用C#开发SQL Function来提供数据 - 天气预报 范例下载 范例程序代码:点此下载 问题情景 开发人员在设计一些数据汇整的系统服务时,可能会选择WCF.WebAPI.Sign ...

  2. ASP.NET MVC自定义AuthorizeAttribute篇知识点讲解—登录限制

    1.前言 a.微软对ASP.NET的开发从WebForm到MVC的转变,已经正式过去5,6个年头,现在WebForm和MVC也都越来越完善,小小算来我也已经工作了将近三年,从大学的时候学习ASP.NE ...

  3. Exchange 2013 、Lync 2013、SharePoint 2013 二

    上一篇简单介绍了安装过程,本篇主要集成 上一篇文章有关于头像的显示问题,engineer  给出了一个连接,介绍了Exchange和Lync的集成过程,根据介绍都配制了一遍. 一.Exchange 和 ...

  4. UDF2

    问题 根据给定的gps点point(x,y)和北京的shape数据,关联出 AOI ID IO 输入 gps点表 create table gps ( x double, //经度 y double ...

  5. 我在用的mac软件(3)-效率篇

    距离上篇博客竟然一晃就2个月过去了……最近确实太忙了,但一忙其实就容易乱,反而积累就少. 今天继续介绍下我在用的mac软件.标题为效率篇,其实没有严格的限定,就是杂乱的介绍我在用的感觉能提升效率的工具 ...

  6. iOS-多线程--介绍NSThread和GCD及其它们的线程通讯示例

    前言:下面就不一一列出 pthread.NSThread.GCD.NSOperation 的完整的各种方法了,只分别将最常用的列出来,以便偶尔瞄一眼. 一.NSThread 1> 线程间的通讯/ ...

  7. linux 2>&1

    2>&1就是用来将标准错误2重定向到标准输出1中的.此处1前面的&就是为了让bash将1解释成标准输出而不是文件1.至于最后一个&,则是让bash在后台执行 例如:/us ...

  8. 使用 ServiceStack.Text 序列化 json 比Json.net更快

    本节将介绍如何使用ServiceStack.Text 来完成高性能序列化和反序列化操作. 在上章构建高性能ASP.NET应用的几点建议 中提到使用高性能类库,有关于JSON序列化的讨论. 在诊断web ...

  9. 【API】短信通106端口验证短信的实现

    信息时代,无论是电商还是网络营(chuan)销(xiao)都希望得道更多的用户信息.所以很多的网站注册上用到了手机验证码功能.网上有很多的SMS接口提供商.在选择的时候无非就是考虑到1.发送速度:2. ...

  10. docker-2 深入了解docker

    docker镜像.容器.仓库的基本概念 镜像 Docker 镜像就是一个只读的模板.例如:一个镜像可以包含一个完整的 CentOS 操作系统环境,里面仅安装了 httpd或用户需要的其它应用程序. 镜 ...