LeetCode Interview Question 01.04. Palindrome Arrangement

Article Directory

1. Topic

  Given a string, write a function to determine whether it is one of the permutations of a palindrome.

  A palindrome is a word or phrase that is the same in both directions. Permutation refers to the rearrangement of letters.

  A palindrome does not have to be a word in a dictionary.

  Click here to jump to the topic .

Example 1:

Input: "tactcoa"
Output: true (arranged with "tacocat", "atcocta", etc.)

2. C# solution

  The permutation of palindromic strings, that is, the number of occurrences of each character in the string is all even, or there is at most one odd number. Therefore, use to numrecord the number of occurrences that is an odd number, and just traverse and update.

  The title here does not specify whether the string is an English letter, so the map size is set to 128.

public class Solution {
    
    
    public bool CanPermutePalindrome(string s) {
    
    
        int[] map = new int[128];     // map 记录表
        int num = 0;                  // 记录奇数次出现字符的个数

        for (int i = 0; i < s.Length; i++) {
    
    
            int index = (int)(s[i]);  // 获取字符的记录位置
            if (map[index] == 0) {
    
     // 出现偶数次,更新记录和 num
                map[index]++;
                num++;
            }
            else {
    
                        // 出现奇数次,同上
                map[index]--;
                num--;
            }
        }

        return num < 2;               // 奇数次出现字符的个数不能 > 1
    }
}
  • Time complexity: O ( n ) O(n)O ( n )

  • Space complexity: O ( 1 ) O(1)O ( 1 ) , depending on how many kinds of characters appear.

おすすめ

転載: blog.csdn.net/zheliku/article/details/132381973