【力扣每日一题】力扣2744最大字符串配对数目

题目来源

力扣2744最大字符串配对数目

题目概述

给你一个下标从 0 开始的数组 words ,数组中包含 互不相同 的字符串。

如果字符串 words[i] 与字符串 words[j] 满足以下条件,我们称它们可以匹配:

字符串 words[i] 等于 words[j] 的反转字符串。 0 <= i < j < words.length 请你返回数组 words 中的 最大 匹配数目。

注意,每个字符串最多匹配一次。

解题思路

将字符串存入哈希表,反转字符串在哈希表中匹配。

代码实现

java实现

public class Solution {
    public int maximumNumberOfStringPairs(String[] words) {
        Map map = new HashMap<>();
        int count = 0;
        for (String word : words) {
            String reverse = reverse(word);
            Integer value = map.get(reverse);
            if (value != null && value > 0) {
                count++;
                map.put(reverse, value - 1);;
            }else {
                map.put(word, 1);
            }
        }
        return count;
    }

    String reverse(String word) {
        char[] chars = new char[word.length()];
        for (int i = 0; i < word.length(); i++) {
            chars[i] = word.charAt(word.length() - 1 - i);
        }
        return new String(chars);
    }
}

c++实现

class Solution {
public:
    int maximumNumberOfStringPairs(vector& words) {
        unordered_map map;
        int count = 0;
        for (string word : words) {
            string reverse = this->reverse(word);
            int value = map[reverse];
            if (value > 0) {
                count++;
                map[reverse] = 0;
            }
            else {
                map[word] = 1;
            }
        }
        return count;
    }
    string reverse(string word) {
        char* chars = new char[word.length()];
        for (int i = 0; i < word.length(); i++) {
            chars[i] = word[word.length() - 1 - i];
        }
        chars[word.length()] = '\0';
        return string(chars);
    }
};

算法题记录

你可能感兴趣的:(leetcode,算法,java,c++)