zoukankan      html  css  js  c++  java
  • [Leetcode] Palindrome Permutation 回文变换

    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?

    哈希表法

    复杂度

    时间 O(N) 空间 O(N)

    思路

    Leetcode的提示其实已经将答案告诉我们了。最笨的方法就是用Permutations的解法,找出所有的Permutation,然后再用Palindrome中判断回文的方法来判断结果中是否有回文。但是我们考察一下回文的性质,回文中除了中心对称点的字符,其他字符都会出现偶数次。而中心对称点如果是字符,该字符会是奇数次,如果在两个字符之间,则所有字符都是出现偶数次。所以,我们只要判断下字符串中每个字符出现的次数,就知道该字符串的其他排列方式中是否有回文了。

    注意

    • 本题也可以用一个HashSet,第偶数个字符可以抵消Set中的字符,最后判断Set的大小是否小于等于1就行了。

    代码

    HashMap实现

    class Solution
    {
    public:
    	bool canPermutePalinedrome(string s)
    	{
    		//hash_map<char, int> mymap;
    		map<char, int> mymap;
    		
    				for (int i = 0; i < s.length(); i++){
    				
    					auto is = mymap.find(s[i]);
    					if (is ==mymap.end()) {
    						//没找到
    						int cnt = 1;
    						mymap.insert(make_pair(s[i],cnt));
    					}
    					else {
    						//找到
    						is->second++;
    					}
    
    
    				}
    				int num_odd=0;
    				for (auto it = mymap.begin();it != mymap.end(); ++it){
    					if (it->second % 2 == 1){
    						num_odd++;
    					}
    					if (num_odd > 1)
    						return false;
    						
    				}
    				return true;
    				
    			}
    };
    

    HashSet实现

    public class Solution {
        public boolean canPermutePalindrome(String s) {
            Set<Character> set = new HashSet<Character>();
            for(int i = 0; i < s.length(); i++){
                // 出现的第偶数次,将其从Set中移出
                if(set.contains(s.charAt(i))){
                    set.remove(s.charAt(i));
                } else {
                // 出现的第奇数次,将其加入Set中
                    set.add(s.charAt(i));
                }
            }
            // 最多只能有一个奇数次字符
            return set.size() <= 1;
        }
    }
  • 相关阅读:
    ORA-04091错误原因与解决方法
    Vue中过滤器及自定义插件
    解决 React 中的 input 输入框在中文输入法下的 bug
    总结18个webpack插件
    使用Vue Composition API写出清晰、可扩展的表单
    实现微前端需要了解的 Vue Genesis 渲染器
    React 监听页面滚动,界面动态显示
    漫谈受控与非受控组件
    vue的完整版和运行时版的区别
    vue中利用provide和inject实现页面刷新(无白屏)重载组件
  • 原文地址:https://www.cnblogs.com/muyangshaonian/p/9650557.html
Copyright © 2011-2022 走看看