LeetCode 266. Palindrome Permutation(对称排列)
来源:互联网 发布:minitab 两组数据分析 编辑:程序博客网 时间:2024/05/01 16:09
原题网址:https://leetcode.com/problems/palindrome-permutation/
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?
方法:统计各个字符的频率。
public class Solution { public boolean canPermutePalindrome(String s) { int[] f = new int[256]; char[] sa = s.toCharArray(); for(int i=0; i<sa.length; i++) f[sa[i]] ++; int even = 0, odd = 0; for(int i=0; i<f.length; i++) { if ((f[i] & 1) == 0) even ++; else odd ++; } if ((sa.length & 1) == 0) { return odd == 0; } else { return odd == 1; } }}
可以进一步优化如下:
public class Solution { public boolean canPermutePalindrome(String s) { char[] sa = s.toCharArray(); int[] f = new int[256]; for(int i=0; i<sa.length; i++) f[sa[i]] ++; boolean single = false; for(int i=0; i<f.length; i++) { if (f[i] % 2 == 1) { if (!single) single = true; else return false; } } return true; }}
0 0
- LeetCode 266. Palindrome Permutation(对称排列)
- LeetCode 267. Palindrome Permutation II(对称排列)
- 回文排列(Palindrome Permutation)
- Leetcode - 266. Palindrome Permutation
- LeetCode 266. Palindrome Permutation
- Leetcode Everyday: 266. Palindrome Permutation
- leetcode-全排列(permutation)
- [leetcode] 266. Palindrome Permutation 解题报告
- Leetcode 266. Palindrome Permutation (Easy) (cpp)
- [Leetcode] 266. Palindrome Permutation 解题报告
- Leetcode: Palindrome Permutation
- *LeetCode-Palindrome Permutation
- [LeetCode 266]Palindrome Permutation
- [Leetcode 266] Palindrome Permutation
- LeetCode 125. Valid Palindrome(校验对称)
- LeetCode | Next Permutation(下一个排列)
- LeetCode 31 Next Permutation(下一个排列)
- LeetCode 31. Next Permutation(下一个排列)
- 解包HIT archive data格式system.img,解决ubiattach: error!: cannot attach mtd0 error 22问题
- 乱码之二 显示的错觉
- [sh2log]Linux键盘记录 keylogger notes
- Python面向对象编程(二)
- 利用nandsim挂载ubi文件系统
- LeetCode 266. Palindrome Permutation(对称排列)
- Android Studio中快速提取方法
- iOS Objective-C基本核心动画,偏移,旋转,缩放,路径,抖动,组动画
- 下载好自动安装
- js之JavaScript 面向对象介绍 ----谷营中西软件科技园
- iOS 引导图的聚光灯效果代码实现
- 码农必须知道的几个名词(持续更新...)
- ViewPager+Fragment组成滑动且带有光标
- Git的下载安装与使用