您的位置:首页 > 其它

算法复习18

2018-01-25 13:19 330 查看
正则表达式匹配

实现一个函数用来匹配包括’.’和’‘的正则表达式。模式中的字符’.’表示任意一个字符,而’‘表示它前面的字符可以出现任意次(包含0次)。匹配是指字符串的所有字符匹配整个模式。例如,字符串”aaa”与模式”a.a”和”ab*ac*a”匹配,但是与”aa.a”和”ab*a”均不匹配

public class Solution {
public boolean match(char[] str, char[] pattern)
{
boolean[][] dp = new boolean[str.length + 1][pattern.length + 1];
dp[0][0] = true;
for (int i = 1; i < dp[0].length; i ++) {
if(pattern[i - 1] == '*') dp[0][i] = dp[0][i - 2];
}
for (int i = 1; i < dp.length; i ++) {
for (int j = 1; j < dp[0].length; j ++) {
if(pattern[j - 1] == '.' || pattern[j - 1] == str[i - 1]) dp[i][j] = dp[i - 1][j - 1];
else if(pattern[j - 1] == '*') {
if(pattern[j - 2] != str[i - 1] && pattern[j - 2] != '.') dp[i][j] = dp[i][j - 2];
else dp[i][j] = dp[i][j - 1] || dp[i][j - 2] || dp[i - 1][j];
}
}
}
return dp[str.length][pattern.length];
}
}


表示数值的字符串

请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。利用正则表达式实现。

public class Solution {
public boolean isNumeric(char[] str) {
String s=String.valueOf(str);
//return s.matches("[+-]?[0-9]*(.[0-9]*)?([eE][+-]?[0-9]+)?");
return s.matches("[+-]?[0-9]*(\\.[0-9]*)?([eE][+-]?[0-9]+)?");
}
}


字符流中第一个不重复的字符

实现一个函数用来找出字符流中第一个只出现一次的字符。

public class Solution {
int count[]=new int[256];
//Insert one char from stringstream
int index=1;
public void Insert(char ch)
{
if(count[ch]==0){
count[ch]=index++;
}
else{
count[ch]=-1;
}
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce()
{
int temp=Integer.MAX_VALUE;
char ch='#';
for(int i=0;i<256;i++){
if(count[i]!=0&&count[i]!=-1&&count[i]<temp){
temp=count[i];
ch=(char)i;
}
}
return ch;
}
}


源代码:https://github.com/ahongl/algorithm.git
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法