主要是如何构造hash表。
public class DeleteChar {
public String delete(String input, String reduce) throws Exception{
assert(true);
char[] s = input.toCharArray();
char[] r = reduce.toCharArray();
HashMap map = new HashMap();
for(char c : r){
map.put(c);
}
StringBuffer sb = new StringBuffer();
for(char c : s){
int i = map.get(c);
if(i == 0){
sb.append(c);
}
}
return sb.toString();
}
private class HashMap{
private int[] a = new int[128];
public void put(char c) throws Exception{
if(c<0 || c>127){
throw new Exception();
}
if(a[c] != 1){
a[c] = 1;
}
}
public int get(char c) throws Exception{
if(c<0 || c>127){
throw new Exception();
}
return a[c];
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
DeleteChar o = new DeleteChar();
String s = null;
try {
s = o.delete("I am a student.", ".aasse");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(s);
}
}
本文介绍了一种使用自定义Hash表实现从源字符串中移除指定字符的方法。通过遍历待减少的字符并将其存入Hash表,再遍历输入字符串以移除已记录的字符,最终返回不含这些字符的新字符串。

被折叠的 条评论
为什么被折叠?



