My short java solution


  • 0

    reference link : https://discuss.leetcode.com/topic/43731/the-best-submission-ever-256ms-in-c-well-commented
    :)

    public class Solution {
        public List<List<Integer>> palindromePairs(String[] words) {
            List<List<Integer>> ret = new ArrayList<List<Integer>>();
            HashMap<String, Integer>  wordmap = new HashMap<>();
            for(int i = 0; i < words.length; i++){
                wordmap.put(words[i], i);
            }
            for(int i = 0; i < words.length; i++){
                String reverse_word = new StringBuilder(words[i]).reverse().toString();
                int len = reverse_word.length();
                for(int j = 0; j <= len; j++){
                    String left = reverse_word.substring(0,j);
                    String right = reverse_word.substring(j, len);
                    if(wordmap.containsKey(left) && i != wordmap.get(left) && isPalind(right) ){
                        ret.add(Arrays.asList(wordmap.get(left), i));
                    }
                    if(j != 0 && wordmap.containsKey(right) && i != wordmap.get(right) && isPalind(left) ){
                        ret.add(Arrays.asList(i,wordmap.get(right)));
                    }
                }
            }
            return ret;
        }
        private boolean isPalind(String word){
            int i = 0, j = word.length() - 1;
            while(i < j){
                if(word.charAt(i++) != word.charAt(j--)){
                    return false;
                }
            }
            return true;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.