91.Decode Ways
public class number {
public static void main(String[] args) {
number object = new number();
// System.out.println(object.numDecodings("622"));//2
// System.out.println(object.numDecodings("123456"));//3
// System.out.println(object.numDecodings("01"));//0
// System.out.println(object.numDecodings("20"));//1
// System.out.println(object.numDecodings("30"));//0
// System.out.println(object.numDecodings("111111"));//13
System.out.println(object.numDecodings("43203072"));//0
}
public int numDecodings(String s) {
int[] dp = new int[s.length() + 1];
dp[0] = 1;
dp[1] = s.charAt(0) == '0' ? 0 : 1;
for (int i = 2; i <= s.length(); i++) {
if (s.charAt(i - 1) != '0')
dp[i] += dp[i - 1];//先看前1位,不为0则相加.在前s[0,i-1]字符后面再加上s[i]这个字符,则dp[i] += dp[i-1]
int val = Integer.valueOf(s.substring(i - 2, i));
if (val >= 10 && val <= 26)
dp[i] += dp[i - 2];//再看前2位,是10-26则相加,在前[0,i-2]字符后面再加上s[i-1,i]这两个字符,则dp[i] += dp[i-2]
System.out.println("i=" + i + ",s.charAt(i - 1):" + s.charAt(i - 1) + ",s.substring(i - 2, i):" + s.substring(i - 2, i) + ",dp[" + i + "]=" + dp[i]);
}
return dp[s.length()];
}
}
给定一个只包含 '(' 和 ')' 的字符串,找出最长的包含有效括号的子串的长度。
示例 1:
输入: "(()"
输出: 2
解释: 最长有效括号子串为 "()"
示例 2:
输入: ")()())"
输出: 4
解释: 最长有效括号子串为 "()()"
class Solution {
public int longestValidParentheses(String s) {
int max = 0;
Stack<Integer> stack = new Stack<>();
stack.push(-1);
for(int i=0;i<s.length();i++){
if('('==s.charAt(i)){
stack.push(i);
} else{
stack.pop();
if(stack.isEmpty()){
stack.push(i);
}else{
max=Math.max(max,i-stack.peek());
}
}
}
return max;
}
}