这次贴上的是盛大公司的笔试题
题目:删除模式串中出现的字符,如“welcome to asted”,模式串为“aeiou”那么得到的字符串为“wlcm t std",要求性能最优。
1、假设这道题目仅仅是对小写字母字符而言,那么本题可以这样做,创建26个桶,每个桶中存放一个标记,标记这个桶中有没有模式串中的字符,这样查找就相当方便了,而这样空间复杂度又不是太大。
package com.interview;
public class PatternDeleteSub {
private static boolean[] bucket = new boolean[26];
public PatternDeleteSub() {
for (int i = 0; i < bucket.length; ++i)
bucket[i] = false;
}
private String patternDeleteSub(String source, String pattern) {
int i = 0;
for (i = 0; i < pattern.length(); ++i)
bucket[pattern.charAt(i) - 'a'] = true;
StringBuilder result = new StringBuilder();
i = 0;
while (i < source.length()) {
char ch = source.charAt(i);
i++;
if (ch <= 'z' && ch >= 'a') {
if (bucket[ch - 'a'])
continue;
else
result.append(ch);
} else
result.append(ch);
}
return result.toString();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
PatternDeleteSub pds = new PatternDeleteSub();
System.out.println(pds.patternDeleteSub("welcome to asted", "aeiou"));
}
}