public class CommonSubSequence { /** * 题目:写一函数f(a,b),它带有两个字符串参数并返回一串字符,该字符串只包含在两个串中都有的并按照在a中的顺序。 * 写一个版本算法复杂度O(N^2)和一个O(N) 。 * * O(N^2):对于a中的每个字符,遍历b中的每个字符,如果相同,则拷贝到新字符串中。 * O(N):首先使用b中的字符建立一个hash_map,对于a中的每个字符,检测hash_map中是否存在,如果存在则拷贝到新字符串中。 * * we do the O(N). * commonSubSequence(String strA,String strB). * 1.In java,"char" is 16 bits.So we make 'int[] count=new int[65536]'. * If a char('x',e.g) shows up in "strB",we set count['x']=1 * 2.Now we iterate "strA".For each char in "strA",'y' for example, * if count['y']=1,we add 'y' to the result sequence. * 3.To avoid duplicate char,we set count['y']=0 after adding 'y' to result sequence. * */ private static final int SIZE=Character.SIZE; public static void main(String[] args) { String a="#abcdefgaaa"; String b="lmnopcxbyacccc"; String c=commonSubSequence(a,b);//abc System.out.println(c); } // return the common sequence of string 'a' and string 'b'.In the order of string 'a' public static String commonSubSequence(String a,String b){ if(a==null||b==null||a.length()==0||b.length()==0){ return null; } int[] c=new int[1<<SIZE];//char[65536].Is it too large? char min=Character.MIN_VALUE; char[] x=a.toCharArray(); char[] y=b.toCharArray(); char[] z=new char[a.length()];//the result char sequence for(int i=0,len=y.length;i<len;i++){ int pos=y[i]-min; c[pos]=1; } int j=0; for(int i=0,len=x.length;i<len;i++){ int pos=x[i]-min; if(c[pos]==1){ c[pos]=0; z[j++]=x[i]; } } return new String(z,0,j); } }