Simple straightforward in-place solution in JAVA (not sure why it is hard level)


  • 0
    I
    public class Solution {
        public List<List<Integer>> palindromePairs(String[] words) {
            
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            for(int i = 0; i < words.length; i++) {
                for(int j = 0; j < words.length; j++) {
                    if(arePal(words[i], words[j]) && i != j) {
                        res.add(Arrays.asList(i, j));
                    }
                }
            }
            
            return res;
        }
        
        boolean arePal(String s1, String s2) {
            
            int i = 0, j = s2.length() - 1;
            while(i < s1.length() && j >= 0) {
                if(s1.charAt(i) != s2.charAt(s2.length() - i - 1)) {
                    return false;
                }
                
                i++;
                j--;
            }
            
            if(i < s1.length()) {
                return isPal(s1, i, s1.length() - 1);
            }
            
            if(j > 0) {
                return isPal(s2, 0, j);
            }
            
            return true;
        }
        
        boolean isPal(String s, int beg, int end) {
            while(beg < end) {
                if(s.charAt(beg) != s.charAt(end)) {
                    return false;
                }
                
                beg++;
                end--;
            }
            
            return true;
        }
    }
    

Log in to reply
 

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