1. 程式人生 > >2015去哪兒網校園招聘筆試題:尋找字串的差異

2015去哪兒網校園招聘筆試題:尋找字串的差異

哪兒的一道筆試題。


給定兩個字串a,b;找出兩個字串中不一樣的字串。如存在於a而不存在於b,則將該字元輸出,同時、加一個“-”標記;若存在於b而不存在於a,則輸出該字元,同時以“+”標記。若是同時存在於a、b中,則不輸出。假設字串是由字母組成。


如:


a="abc",b="aabcbc",則輸出為"+a,+b,+c";

a="abcde",b="bcdef",則輸出為“-a,+f”;

思路:


我們可以使用上一篇講到的尋找兩個字串的公共子串的方法。即先找到兩個字串的最長公共子串,做相應的處理,然後找次長的公共子串,做相同的處理;直到兩個字串沒有公共子串。

package com.liuhao.acm.exam;

public class StringDiff {

	public String diff(String a, String b){
		String result = "";
		LongestComSub lcs = new LongestComSub();
		
		while(true){
		
			//獲取兩個字串的最長公共子串
			String maxSub = lcs.getLongestComSub(a, b);
			
			//若沒有公共子串,則跳出while
			if(maxSub.length() == 0){
				break;
			}
			
			//將公共子串全部替換掉
			a = a.replaceAll(maxSub, "0");
			b = b.replaceAll(maxSub, "1");
			
		}
		
		//將a中剩下的輸出
		for(int i=0; i<a.length();i++){
			if(a.charAt(i) != '0'){
				result += ("-" + a.charAt(i) + ",");
			}
		}
		
		for(int i=0; i<b.length();i++){
			if(b.charAt(i) != '1'){
				result += ("+" + b.charAt(i) + ",");
			}
		}
		
		result = result.substring(0, result.length()-1);
		
		return result;
	}
	
	public static void main(String[] args) {
		String a = "abcbc";
		String b = "aabcaa";
		System.out.println(new StringDiff().diff(a, b));
	}
	
}