第30天--算法(Leetcode 124,125,127)
124.二叉树的最大路径和
public int maxPathSum(TreeNode root) { if(root == null) { return 0; } return process(root).max; } public Info process(TreeNode root) { if(root == null) { return null; } Info left = process(root.left); Info right = process(root.right); int beginX = root.val; int max = root.val; if(left != null) { beginX = Math.max(beginX,root.val + left.beginX); max = Math.max(max,left.max); } if(right != null) { beginX = Math.max(beginX,root.val + right.beginX); max = Math.max(max,right.max); } max = Math.max(beginX,max); if(left != null && right != null) { max = Math.max(max,left.beginX + root.val + right.beginX); }return new Info(beginX,max); } class Info { int beginX; int max; public Info(int beginX,int max) { this.beginX = beginX; this.max = max; } } 125.验证回文串 public boolean isPalindrome(String s) { if(s == null || s.length() == 0) { return true; } char s1[] = s.toCharArray(); int L = 0; int R = s1.length - 1; while(L < R) { if(isValidChar(s1[L]) && isValidChar(s1[R])) { if(!isEqual(s1[L],s1[R])) { return false; } L ++; R --; }else { if(!isValidChar(s1[L])) { L ++; } if(!isValidChar(s1[R])) { R --; } } } return true; } public boolean isValidChar(char c) { if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) { return true; } return false; } public boolean isEqual(char c1,char c2) { return String.valueOf(c1).equalsIgnoreCase(String.valueOf(c2)); } 127.单词接龙 public int ladderLength(String beginWord, String endWord, List