ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

336. 回文对

2022-01-19 23:00:27  阅读:117  来源: 互联网

标签:word int 336 ret length words new 回文


给定一组 互不相同 的单词, 找出所有 不同 的索引对 (i, j),使得列表中的两个单词, words[i] + words[j] ,可拼接成回文串。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-pairs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

枚举前缀后缀

import java.util.*;

class Solution {
    Map<String, Integer> indices = new HashMap<String, Integer>();

    public List<List<Integer>> palindromePairs(String[] words) {
        int n = words.length;
        for (int i = 0; i < n; ++i) {
            indices.put(new StringBuffer(words[i]).reverse().toString(), i);

        }

        List<List<Integer>> ret = new ArrayList<List<Integer>>();
        for (int i = 0; i < n; i++) {
            String word = words[i];
            int m = words[i].length();
            for (int j = 0; j <= m; j++) {
                if (isPalindrome(word, j, m - 1)) {
                    int leftId = findWord(word, 0, j - 1);
                    if (leftId != -1 && leftId != i) {
                        ret.add(Arrays.asList(i, leftId));
                    }
                }
                if (j != 0 && isPalindrome(word, 0, j - 1)) {
                    int rightId = findWord(word, j, m - 1);
                    if (rightId != -1 && rightId != i) {
                        ret.add(Arrays.asList(rightId, i));
                    }
                }
            }
        }
        return ret;
    }

    public boolean isPalindrome(String s, int left, int right) {
        while (left < right) {
            if (s.charAt(left++) != s.charAt(right--)) {
                return false;
            }
        }
        return true;
    }

    public int findWord(String s, int left, int right) {
        return indices.getOrDefault(s.substring(left, right + 1), -1);
    }
}

字典树 + Manacher

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {

    private static String enrich(String word) {
        StringBuffer sb = new StringBuffer();
        sb.append('$');
        for (int i = 0; i < word.length(); ++i) {
            sb.append(word.charAt(i)).append('$');
        }
        return sb.toString();
    }

    private static boolean[][] getPalindromePrefixAndSuffix(String word) {
        if (word == null || word.length() == 0) {
            return new boolean[2][0];
        }
        boolean[][] ret = new boolean[2][word.length()];
        word = enrich(word);
        int[] p = new int[word.length()];
        int c = -1;
        int r = -1;

        // 0 1 2 3 4 5 6
        // # 1 # 1 # 1 #
        for (int i = 0; i < word.length(); ++i) {
            p[i] = i > r ? 1 : Math.min(p[2 * c - i], r - i + 1);
            while (i + p[i] < word.length() && i - p[i] >= 0 && word.charAt(i + p[i]) == word.charAt(i - p[i])) {
                p[i]++;
            }
            if (i + p[i] - 1 > r) {
                r = i + p[i] - 1;
                c = i;
            }

            if (i != 0 && i != word.length() - 1) {
                if (i - p[i] + 1 == 0) {
                    ret[0][(i + p[i] - 2) >> 1] = true;
                }

                if (i + p[i] == word.length()) {
                    ret[1][(i - p[i] + 2) >> 1] = true;
                }
            }
        }
        return ret;
    }

    /**
     * O(n * m)
     *
     * @param words
     * @return
     */
    private static List<List<Integer>> solve(String[] words) {

        List<List<Integer>> ret = new ArrayList<>();

        Trie prefixTrie = new Trie();
        Trie suffixTrie = new Trie();

        for (int i = 0; i < words.length; ++i) {
            prefixTrie.insert(words[i], i);
            suffixTrie.insert(new StringBuilder(words[i]).reverse().toString(), i);
        }

        for (int i = 0; i < words.length; ++i) {
            String word = words[i];

            boolean[][] palindromePrefixAndSuffix = getPalindromePrefixAndSuffix(word);

            boolean[] prefix = palindromePrefixAndSuffix[0];
            boolean[] suffix = palindromePrefixAndSuffix[1];

            int[] suffixIndex = suffixTrie.query(word);

            int[] prefixIndex = prefixTrie.query(new StringBuilder(word).reverse().toString());

            int m = word.length();

            /**
             * 是否存在word完全逆序的字符串
             */
            if (suffixIndex[m] != -1 && suffixIndex[m] != i) {
                ret.add(Arrays.asList(i, suffixIndex[m]));
            }

            for (int j = 0; j < m; ++j) {
                /**
                 * word字符串 [0, j] 为回文串
                 * 需要 [j+1, m) 的字符串逆序后拼接到前面
                 */
                if (prefix[j]) {
                    if (prefixIndex[m - j - 1] != -1 && prefixIndex[m - j - 1] != i) {
                        ret.add(Arrays.asList(prefixIndex[m - j - 1], i));
                    }
                }

                /**
                 * word字符串 [j, m)为回文串
                 * 需要 [0, j-1] 的字符串逆序后拼接到后面
                 */
                if (suffix[j]) {
                    if (suffixIndex[j] != -1 && suffixIndex[j] != i) {
                        ret.add(Arrays.asList(i, suffixIndex[j]));
                    }
                }
            }
        }

        return ret;
    }

    public static List<List<Integer>> palindromePairs(String[] words) {
        if (words == null || words.length == 0) {
            return new ArrayList<>(0);
        }

        return solve(words);
    }
}

class Trie {

    private Node root;

    static class Node {
        Node[] children = new Node[26];
        int index = -1;
    }

    public Trie() {
        this.root = new Node();
    }

    public void insert(String word, int index) {
        Node p = root;
        for (int i = 0; i < word.length(); ++i) {
            int path = word.charAt(i) - 'a';
            if (p.children[path] == null) {
                p.children[path] = new Node();
            }
            p = p.children[path];
        }
        p.index = index;
    }

    public int[] query(String word) {
        Node p = root;
        int[] ret = new int[word.length() + 1];
        Arrays.fill(ret, -1);
        ret[0] = root.index;
        for (int i = 0; i < word.length(); ++i) {
            int path = word.charAt(i) - 'a';
            if (p.children[path] == null) {
                break;
            }
            p = p.children[path];
            ret[i + 1] = p.index;
        }
        return ret;
    }
}

标签:word,int,336,ret,length,words,new,回文
来源: https://www.cnblogs.com/tianyiya/p/15824535.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有