计算字符串之间的相似度(递归)

可操作规则:

1,修改一个字符('a' 变 'b')

2,增加一个字符("adbb" 变"aebbd")

3,删除一个字符("travelling" 变 "traveling")

求字符串strA变成strB的最少变换次数。

 

package JiaNan;
public class Main 
{
	static int CalStrDistance(String strA,int pABegin,int pAEnd,String strB,int pBBegin,int pBEnd)
	{
		if(pABegin > pAEnd)
		{
		    if(pBBegin > pBEnd)
		    	return 0;
		    else
		    	return pBEnd - pBBegin +1;
		}
		if(pBBegin > pBEnd)
		{
		    if(pABegin > pAEnd)
		    	return 0;
		    else
		    	return pAEnd - pABegin + 1;
		}
		if(strA.charAt(pABegin) == strB.charAt(pBBegin))
		{
			return CalStrDistance(strA,pABegin+1,pAEnd,strB,pBBegin+1,pBEnd);
		}
		else
		{
			 int t1 = CalStrDistance(strA,pABegin,pAEnd,strB,pBBegin+1,pBEnd);
			 int t2 = CalStrDistance(strA,pABegin+1,pAEnd,strB,pBBegin,pBEnd);
			 int t3 = CalStrDistance(strA,pABegin+1,pAEnd,strB,pBBegin+1,pBEnd);
			 return minValue(t1,t2,t3) + 1;
		}
	}
	static int minValue(int t1, int t2, int t3) 
	{
		// TODO Auto-generated method stub
		int min = t1 < t2 ? t1 : t2;
		min = min < t3 ? min : t3;
		return min;
	}
	public static void main(String[] args)
	{
		
		String strA = "abcfh";
		String strB = "abcdefgh";
		System.out.println(CalStrDistance(strA,0,strA.length()-1,strB,0,strB.length()-1));
	}
}

/*
3
*/

这个求的是最少变化次数,那就感觉比较有意思了,我利用一个min函数 + 递归  那求出来的就是最少变换次数。按照以前的想法,往往会用变量啥的记录每一种变换完成的次数,然后比较大小,这种递归思路我想以后肯定会有很多用处。 

 

 

 

你可能感兴趣的:(【数据结构+算法】)