Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

336. Palindrome Pairs #285

Open
Tcdian opened this issue Aug 6, 2020 · 1 comment
Open

336. Palindrome Pairs #285

Tcdian opened this issue Aug 6, 2020 · 1 comment
Labels

Comments

@Tcdian
Copy link
Owner

Tcdian commented Aug 6, 2020

336. Palindrome Pairs

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

Example 1

Input: ["abcd","dcba","lls","s","sssll"]
Output: [[0,1],[1,0],[3,2],[2,4]] 
Explanation: The palindromes are ["dcbaabcd","abcddcba","slls","llssssll"]

Example 2

Input: ["bat","tab","cat"]
Output: [[0,1],[1,0]] 
Explanation: The palindromes are ["battab","tabbat"]
@Tcdian Tcdian added the String label Aug 6, 2020
@Tcdian
Copy link
Owner Author

Tcdian commented Aug 6, 2020

Solution ( 暴力解法 )

  • JavaScript Solution
/**
 * @param {string[]} words
 * @return {number[][]}
 */
var palindromePairs = function(words) {
    const reuslt = [];
    for (let i = 0; i < words.length; i++) {
        for (let j = 0; j < words.length; j++) {
            if (i === j) {
                continue;
            }
            if (isPalindrome(`${words[i]}${words[j]}`)) {
                reuslt.push([i, j]);
            }
        }
    }
    return reuslt;
};

function isPalindrome(word) {
    let left = 0;
    let right = word.length - 1;
    while(left < right) {
        if (word[left] !== word[right]) {
            return false;
        }
        left++;
        right--;
    }
    return true;
}
  • TypeScript Solution
function palindromePairs(words: string[]): number[][] {
    const reuslt: number[][] = [];
    for (let i = 0; i < words.length; i++) {
        for (let j = 0; j < words.length; j++) {
            if (i === j) {
                continue;
            }
            if (isPalindrome(`${words[i]}${words[j]}`)) {
                reuslt.push([i, j]);
            }
        }
    }
    return reuslt;
};

function isPalindrome(word: string): boolean {
    let left = 0;
    let right = word.length - 1;
    while(left < right) {
        if (word[left] !== word[right]) {
            return false;
        }
        left++;
        right--;
    }
    return true;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant