My function is accepted but I feel it's not that efficient, anyone can show me your solution?


  • 0
    K
    public class Solution {
        public String longestPalindrome(String s) {
            char[] ch = s.toCharArray();
            
            int max = 0;
            int start = 0;
            
            if (ch.length == 1) {
                return s;
            }
            
            for (int i = 0; i < ch.length; i++) {
                // cover the case like: abccba
                int tempMax = 0;
                int tempStart = i;
                int tempEnd = i + 1;
                
                while(tempStart >= 0 && tempEnd <= ch.length - 1 && ch[tempStart] == ch[tempEnd]) {
                    tempMax += 2;
                    
                    if (tempMax > max) {
                        max = tempMax;
                        start = tempStart;
                    }
                    
                    tempStart--;
                    tempEnd++;
                }
                
                // cover the case like : abcdcba
                tempStart = i - 1;
                tempEnd = i + 1;
                tempMax = 1;
                
                while(tempStart >= 0 && tempEnd <= ch.length - 1 && ch[tempStart] == ch[tempEnd]) {
                    tempMax += 2;
                    
                    if (tempMax > max) {
                        max = tempMax;
                        start = tempStart;
                    }
                    
                    tempStart--;
                    tempEnd++;
                }
            }
            
            
            return s.substring(start, start + max);
        }
        
        
    }

  • 0

    anyone can show me your solution?

    Have a look at the dozens already posted right here for this problem?


Log in to reply
 

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