zoukankan      html  css  js  c++  java
  • 回文字符串系列问题

    关于回文字符串会有很多算法题,下面收集了一些常见的算法。

    [LeetCode] Palindrome Pairs 回文对

    Given a list of unique words, find all pairs of distinct indices (i, j) in the given list, so that the concatenation of the two words, i.e.words[i] + words[j] is a palindrome.

    Example 1:
    Given words = ["bat", "tab", "cat"]
    Return [[0, 1], [1, 0]]
    The palindromes are ["battab", "tabbat"]

    Example 2:
    Given words = ["abcd", "dcba", "lls", "s", "sssll"]
    Return [[0, 1], [1, 0], [3, 2], [2, 4]]
    The palindromes are ["dcbaabcd", "abcddcba", "slls", "llssssll"]
    分析:这道题给我们了许多单词,让我们找出回文对,就是两个单词拼起来是个回文字符串,要用到哈希表来建立每个单词和其位置的映射,然后需要一个set来保存出现过的单词的长度,算法的思想是,遍历单词集,对于遍历到的单词,我们对其翻转一下,然后在哈希表查找翻转后的字符串是否存在,注意不能和原字符串的坐标位置相同,因为有可能一个单词翻转后和原单词相等,现在我们只是处理了bat和tab的情况,还存在abcd和cba,dcb和abcd这些情况需要考虑,这就是我们为啥需要用set,由于set是自动排序的,我们可以找到当前单词长度在set中的iterator,然后从开头开始遍历set,遍历比当前单词小的长度,比如abcdd翻转后为ddcba,我们发现set中有长度为3的单词,然后我们检查dd是否为回文串,若是,再看cba是否存在于哈希表,若存在,则说明abcdd和cba是回文对,存入结果中,对于dcb和aabcd这类的情况也是同样处理,我们要在set里找的字符串要在遍历到的字符串的左边和右边分别尝试,看是否是回文对,这样遍历完单词集,就能得到所有的回文对,参见代码如下:

     

     1 class Solution {
     2 public:
     3     vector<vector<int>> palindromePairs(vector<string>& words) {
     4         vector<vector<int>> res;
     5         unordered_map<string, int> m;
     6         set<int> s;
     7         for (int i = 0; i < words.size(); ++i) {
     8             m[words[i]] = i;
     9             s.insert(words[i].size());
    10         }
    11         for (int i = 0; i < words.size(); ++i) {
    12             string t = words[i];
    13             int len = t.size();
    14             reverse(t.begin(), t.end());
    15             if (m.count(t) && m[t] != i) {
    16                 res.push_back({i, m[t]});
    17             }
    18             auto a = s.find(len);
    19             for (auto it = s.begin(); it != a; ++it) {
    20                 int d = *it;
    21                 if (isValid(t, 0, len - d - 1) && m.count(t.substr(len - d))) {
    22                     res.push_back({i, m[t.substr(len - d)]});
    23                 }
    24                 if (isValid(t, d, len - 1) && m.count(t.substr(0, d))) {
    25                     res.push_back({m[t.substr(0, d)], i});
    26                 }
    27             }
    28         }
    29         return res;
    30     }
    31     bool isValid(string t, int left, int right) {
    32         while (left < right) {
    33             if (t[left++] != t[right--]) return false;
    34         }
    35         return true;
    36     }
    37 };

     

     

  • 相关阅读:
    把KB转化为KB及以上单位
    php自动获取上一个月的起始时间
    CentOS 7.2mini版本下编译安装php7.4.6+MySQL5.7.14+Nginx1.18.0
    JS 根据子网掩码,网关计算出所有的IP范围
    php 在字符串指定位置插入新字符
    PHP实现文件下载
    JS 日期与时间戳相互转化
    MySQL中有关char、varchar、int、tinyint、decimal
    数据库设计三范式
    利用递归实现 两个队列实现一个栈的教程 写的超级详细小白都能看懂!
  • 原文地址:https://www.cnblogs.com/SarahLiu/p/6026547.html
Copyright © 2011-2022 走看看