正则表达式匹配
- 动态规划。建立一个二维数组dp[len1+1][len2+1]来判断从字符串i处与模式串j处是否匹配,如果匹配则置dp[i][j]为true,如果不匹配则再判断模式串是否为*和'.',如果不是那就取false,是.直接判断为ture;如果是*则再判断字符串能否跟上一个位置的匹配串匹配,或者上一个匹配串是‘.’,如果成功匹配那置true,如果无法匹配那也相当于匹配0次,也置为true。
class Solution {
public boolean isMatch(String s, String p) {
char []ch1 = s.toCharArray();
char []ch2 = p.toCharArray();
int len1 = s.length();
int len2 = p.length();
boolean [][]dp = new boolean[len1 + 1][len2 + 1];
dp[0][0] = true;
for (int j = 0; j < len2; j++) {
if (ch2[j] == '*') {
dp[0][j + 1] = dp[0][j - 1];
}
}
for(int i = 0; i < len1; i++){
for(int j = 0; j< len2; j++){
if(ch1[i] == ch2[j] || ch2[j] == '.'){
dp[i+1][j+1] = dp[i][j];
}else if(ch2[j] == '*'){
if(ch1[i] == ch2[j - 1] || ch2[j - 1] == '.'){
dp[i + 1][j + 1] = dp[i + 1][j - 1] || dp[i][j + 1];
}else{
dp[i+1][j+1] = dp[i+1][j-1];
}
}
}
}
return dp[len1][len2];
}
}
盛最多水的容器
- 双指针法,由于容器的高度由短板决定,所以如果我们向内移动长板,得到的容积只会变小,所以我们不断移动两块板子中的短板直到两指针相遇即可。
class Solution {
public int maxArea(int[] height) {
int i = 0, j = height.length - 1, res = 0;
while(i < j) {
res = height[i] < height[j] ?
Math.max(res, (j - i) * height[i++]):
Math.max(res, (j - i) * height[j--]);
}
return res;
}
}
罗马数字转整数
class Solution {
public int romanToInt(String s) {
char []ch = s.toCharArray();
int len = s.length();
int res = 0;
for(int i = 0; i<len; i++){
if(ch[i] == 'M'){
res += 1000;
}else if(ch[i] == 'D'){
res += 500;
}else if(ch[i] == 'C'){
if(i + 1 < len){
if(ch[i+1] == 'D'){
res += 400;
i++;
}else if(ch[i+1] == 'M'){
res += 900;
i++;
}else{
res += 100;
}
}else{
res += 100;
}
}else if(ch[i] == 'L'){
res += 50;
}else if(ch[i] == 'X'){
if(i + 1 < len){
if(ch[i+1] == 'L'){
res += 40;
i++;
}else if(ch[i+1] == 'C'){
res += 90;
i++;
}else{
res += 10;
}
}else{
res += 10;
}
}else if(ch[i] == 'V'){
res += 5;
}else if(ch[i] == 'I'){
if(i + 1 < len){
if(ch[i+1] == 'V'){
res += 4;
i++;
}else if(ch[i+1] == 'X'){
res += 9;
i++;
}else{
res += 1;
}
}else{
res += 1;
}
}
}
return res;
}
}