From 44a5919c0ba0f18a838b036657d08228579f17c4 Mon Sep 17 00:00:00 2001 From: yuanguangxin <274841922@qq.com> Date: Sat, 15 Feb 2020 02:33:32 +0800 Subject: [PATCH] update q10/q746 --- .idea/workspace.xml | 38 +++++++++++++------------- src/q10/Solution.java | 61 +++++++++--------------------------------- src/q746/Solution.java | 6 ++--- 3 files changed, 34 insertions(+), 71 deletions(-) diff --git a/.idea/workspace.xml b/.idea/workspace.xml index 62443b0..cce2e36 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -2,17 +2,9 @@ - - - - - - - - - - + + @@ -363,7 +362,8 @@ - @@ -378,14 +378,14 @@ - + - - + + - + @@ -430,10 +430,10 @@ - + - + diff --git a/src/q10/Solution.java b/src/q10/Solution.java index 245dc27..b973a65 100644 --- a/src/q10/Solution.java +++ b/src/q10/Solution.java @@ -1,57 +1,20 @@ package q10; +/** + * 回溯法 对于*字符,可以直接忽略模式串中这一部分,或者删除匹配串的第一个字符,前提是它能够匹配模式串当前位置字符,即 pattern[0]。如果两种操作中有任何一种使得剩下的字符串能匹配,那么初始时,匹配串和模式串就可以被匹配。 + */ public class Solution { - public boolean isMatch(String s, String p) { - int i = 0; - int j = 0; - while (i < s.length()) { - char sc = s.charAt(i); - if (j >= p.length()) { - return false; - } - char pc = p.charAt(j); + public boolean isMatch(String text, String pattern) { + if (pattern.isEmpty()) return text.isEmpty(); + boolean firstMatch = (!text.isEmpty() && + (pattern.charAt(0) == text.charAt(0) || pattern.charAt(0) == '.')); - if (j + 1 < p.length()) { - if (p.charAt(j + 1) == '*') { - if (pc == '.') { - j+=2; - break; - } else if (pc == sc) { - while (i < s.length() && s.charAt(i) == pc) { - i++; - } - } - j += 2; - } else { - if ((sc == pc) || (pc == '.')) { - i++; - j++; - } else { - return false; - } - } - } else { - if ((sc == pc) || (pc == '.')) { - i++; - j++; - } else { - return false; - } - } + if (pattern.length() >= 2 && pattern.charAt(1) == '*') { + return (isMatch(text, pattern.substring(2)) || + (firstMatch && isMatch(text.substring(1), pattern))); + } else { + return firstMatch && isMatch(text.substring(1), pattern.substring(1)); } - - while (j < p.length()) { - if (p.charAt(j) == '*') { - j++; - } else { - if (j + 1 < p.length() && p.charAt(j) == '*') { - j += 2; - } else { - return false; - } - } - } - return true; } public static void main(String[] args) { diff --git a/src/q746/Solution.java b/src/q746/Solution.java index 12d292f..20f1906 100644 --- a/src/q746/Solution.java +++ b/src/q746/Solution.java @@ -1,5 +1,8 @@ package q746; +/** + * 动态规划 o(n) f[i] = cost[i] + min(f[i+1], f[i+2]) + */ class Solution { public int minCostClimbingStairs(int[] cost) { int f1 = 0, f2 = 0; @@ -7,9 +10,6 @@ class Solution { int f0 = cost[i] + Math.min(f1, f2); f2 = f1; f1 = f0; - System.out.println("f0=" + f0); - System.out.println("f2=" + f2); - System.out.println("f1=" + f1); } return Math.min(f1, f2); }