边工作边刷题:70天一遍leetcode: day 80
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的更多相关文章
- 边工作边刷题:70天一遍leetcode: day 89
Word Break I/II 现在看都是小case题了,一遍过了.注意这题不是np complete,dp解的time complexity可以是O(n^2) or O(nm) (取决于inner ...
- 边工作边刷题:70天一遍leetcode: day 77
Paint House I/II 要点:这题要区分房子编号i和颜色编号k:目标是某个颜色,所以min的list是上一个房子编号中所有其他颜色+当前颜色的cost https://repl.it/Chw ...
- 边工作边刷题:70天一遍leetcode: day 78
Graph Valid Tree 要点:本身题不难,关键是这题涉及几道关联题目,要清楚之间的差别和关联才能解类似题:isTree就比isCycle多了检查连通性,所以这一系列题从结构上分以下三部分 g ...
- 边工作边刷题:70天一遍leetcode: day 85-3
Zigzag Iterator 要点: 实际不是zigzag而是纵向访问 这题可以扩展到k个list,也可以扩展到只给iterator而不给list.结构上没什么区别,iterator的hasNext ...
- 边工作边刷题:70天一遍leetcode: day 101
dp/recursion的方式和是不是game无关,和game本身的规则有关:flip game不累加值,只需要一个boolean就可以.coin in a line II是从一个方向上选取,所以1d ...
- 边工作边刷题:70天一遍leetcode: day 1
(今日完成:Two Sum, Add Two Numbers, Longest Substring Without Repeating Characters, Median of Two Sorted ...
- 边工作边刷题:70天一遍leetcode: day 70
Design Phone Directory 要点:坑爹的一题,扩展的话类似LRU,但是本题的accept解直接一个set搞定 https://repl.it/Cu0j # Design a Phon ...
- 边工作边刷题:70天一遍leetcode: day 71-3
Two Sum I/II/III 要点:都是简单题,III就要注意如果value-num==num的情况,所以要count,并且count>1 https://repl.it/CrZG 错误点: ...
- 边工作边刷题:70天一遍leetcode: day 71-2
One Edit Distance 要点:有两种解法要考虑:已知长度和未知长度(比如只给个iterator) 已知长度:最好不要用if/else在最外面分情况,而是loop在外,用err记录misma ...
随机推荐
- php中的常用数组函数(一)(比较多个数组的差集的函数们 array_diff_assoc() array_diff() array_diff_key() array_diff_ukey() array_diff_uassoc())
array_diff_assoc($arr1, $arr2, $arr3,... n); 返回:一个$arr1的副本,后续的数组中出现一个键值相同的元素,就在副本中删掉这个元素,最后返回这个副本. 如 ...
- css中的定位和框模型问题
和定位有关的元素属性如下 position 元素的定位类型 绝对定位会相对于最近定位的祖先元素的位置来定位,而不会影响其他框的位置 固定定位 相对定位 z-index 元素的堆叠顺序 值越大 ...
- mysql乱码以及Data too long for column全解(最完整实用版)
今天系统升级,开发.测试说本地环境.测试环境都没有问题,都用ssh client升的,演示环境报错了Data too long for column. 仔细检查了下,表字符集都是utf-8,目测长度肯 ...
- H5前端面试题及答案(1)
前几天去面试了一家公司,整下改公司的面试题. 1.新的 HTML5 文档类型和字符集是? HTML5 文档类型很简单: <!doctype html> HTML5 使用 UTF-8 编码示 ...
- JavaScript基础14——js的Math对象
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- Engine中如何更改lyr文件数据源的相对路径
以下是使用relativebase存储layerfile的代码,如果需要修改数据源只要修改ILayer即可: string folderpath = @E:相对路径; string layerfile ...
- Android 5中不同效果的Toast
一.运行的结果 二.主要的代码 package com.otn.android.toast; import java.util.Timer; import java.util.TimerTask; i ...
- 【转】IOS屏幕旋转与View的transform属性之间的关系,比较底层
iTouch,iPhone,iPad设置都是支持旋转的,如果我们的程序能够根据不同的方向做出不同的布局,体验会更好. 如何设置程序支持旋转呢,通常我们会在程序的info.plist中进行设置Suppo ...
- Web应用程序系统的多用户权限控制设计及实现-首页模块【5】
首页模块就是展示不同权限的最终结果了,在阅读这章之前若有些不明白,可看看后续的单独的权限模块,用户模块,目录模块后从整体上再看首页模块. 阅读该模块需要一定或者是比较熟练的js知识,EasyUI Ta ...
- iOSQuartz2D-04-手动剪裁图片并保存到相册
实现效果 操作步骤 绘制一个矩形框,弹出一个alertView,提示是否保存图片 点击"是",将图片保存到相册 在相册中查看保存的图片 效果图 实现思路 在控制器的view上添加一 ...