博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Palindrome Permutation
阅读量:6484 次
发布时间:2019-06-23

本文共 1119 字,大约阅读时间需要 3 分钟。

Problem Description:

Given a string, determine if a permutation of the string could form a palindrome.

For example,

"code" -> False, "aab" -> True, "carerac" -> True.

Hint:

      1. Consider the palindromes of odd vs even length. What difference do you notice?
      2. Count the frequency of each character.
      3. If each character occurs even number of times, then it must be a palindrome. How about character which occurs odd number of times?

Just check there are no more than 2 characters that appear an odd number of times in the string.

My C++ code using an array as a hash map is as follows.

1 class Solution {2 public:3     bool canPermutePalindrome(string s) {4         int odd = 0, counts[256] = {
0};5 for (char c : s)6 odd += ++counts[c] & 1 ? 1 : -1;7 return odd <= 1;8 }9 };

BTW, Stefan has posted many nice solutions , including the following one that uses bitset.

1 class Solution {2 public:3     bool canPermutePalindrome(string s) {4         bitset<256> b;5         for (char c : s) b.flip(c);6         return b.count() < 2;7     }8 };

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4748554.html

你可能感兴趣的文章
能力不是仅靠原始积累(三)
查看>>
彻底学会使用epoll(一)——ET模式实现分析
查看>>
脱离标准文档流(2)---定位
查看>>
IO流之字符流
查看>>
集合异常之List接口
查看>>
Softmax回归
查看>>
紫书 习题11-11 UVa 1644 (并查集)
查看>>
App工程结构搭建:几种常见Android代码架构分析
查看>>
使用openssl进行证书格式转换
查看>>
Callable和Future
查看>>
少用数字来作为参数标识含义
查看>>
ScrollView中嵌套ListView
查看>>
观察者模式
查看>>
在properties.xml中定义变量,在application.xml中取值问题
查看>>
cell reuse & disposebag
查看>>
【故障处理】ORA-12545: Connect failed because target host or object does not exist
查看>>
js判断移动端是否安装某款app的多种方法
查看>>
学习angularjs的内置API函数
查看>>
4、输出名称 Exported names
查看>>
Pre-echo(预回声),瞬态信号检测与TNS
查看>>