- 论坛徽章:
- 0
|
- /**
- *两个字符串,通过删除/添加/修改变为相同的字符串的最少操作
- *字符串距离就是:操作+1
- *字符串的相似度为(1/操作+1)
- * */
- #include <iostream>
- #include <chrono>
- using namespace std;
- using namespace std::chrono;
- int get_distance(char* left,int l_begin,int l_end,
- char* right,int r_begin,int r_end)
- {
- if(l_begin>=l_end)
- {
- if(r_begin>=r_end)
- return 0;
- else
- return r_end-r_begin;
- }
- if(r_begin>=r_end)
- {
- if(l_begin>=l_end)
- return 0;
- else
- return l_end-l_begin;
- }
- if(left[l_begin]==right[r_begin])
- return get_distance(left,l_begin+1,l_end,
- right,r_begin+1,r_end);
- else
- {
- int op1=get_distance(left,l_begin+1,l_end,
- right,r_begin+1,r_end);
- int op2=get_distance(left,l_begin,l_end,
- right,r_begin+1,r_end);
- int op3=get_distance(left,l_begin+1,l_end,
- right,r_begin,r_end);
- int sum=[&]()
- {
- int mid;
- if(op1>=op2)
- mid=op2;
- else
- mid=op1;
- if(mid>op3)
- mid=op3;
- return mid+1;
- }();
- return sum;
- }
- }
- int** new_matrix(int l,int r)
- {
- int** ptr=new int*[l];
- for(int i=0;i<l;++i)
- {
- ptr[i]=new int[r];
- for(int j=0;j<r;++j)
- {
- ptr[i][j]=-1;
- }
- }
- return ptr;
- }
- void delete_matrix(int** ptr,int l)
- {
- for(int i=0;i<l;++i)
- delete[] ptr[i];
- delete[] ptr;
- }
- int get_distance_state(char* left,int l_begin,int l_end,
- char* right,int r_begin,int r_end,int** state)
- {
- if(state[l_begin][r_begin]!=-1)
- return state[l_begin][r_begin];
- if(l_begin>=l_end)
- {
- if(r_begin>=r_end)
- {
- state[l_begin][r_begin]=0;
- return 0;
- }
- else
- {
- int dis=r_end-r_begin;
- state[l_begin][r_begin]=dis;
- return dis;
- }
- }
- if(r_begin>=r_end)
- {
- if(l_begin>=l_end)
- {
- state[l_begin][r_begin]=0;
- return 0;
- }
- else
- {
- int dis= l_end-l_begin;
- state[l_begin][r_begin]=dis;
- return dis;
- }
- }
- if(left[l_begin]==right[r_begin])
- {
- int dis=get_distance(left,l_begin+1,l_end,
- right,r_begin+1,r_end);
- state[l_begin][r_begin]=dis;
- return dis;
- }
- else
- {
- int op1=get_distance(left,l_begin+1,l_end,
- right,r_begin+1,r_end);
- int op2=get_distance(left,l_begin,l_end,
- right,r_begin+1,r_end);
- int op3=get_distance(left,l_begin+1,l_end,
- right,r_begin,r_end);
- int sum=[&]()
- {
- int mid;
- if(op1>=op2)
- mid=op2;
- else
- mid=op1;
- if(mid>op3)
- mid=op3;
- return mid+1;
- }();
- state[l_begin][r_begin]=sum;
- return sum;
- }
- }
- int main(int argc,char* argv[])
- {
- char left[]={"123456"};
- char right[]={"abcd"};
-
- int** state=new_matrix(sizeof(left)/sizeof(char),
- sizeof(right)/sizeof(char));
- int dis=get_distance_state(left,0,sizeof(left)/sizeof(char),
- right,0,sizeof(right)/sizeof(char),state);
- cout<<"with state: "<<dis<<endl;
- delete_matrix(state,sizeof(left)/sizeof(char));
- }
复制代码 楼主代码有问题吧?!
以上是我的代码- g++ -g -Wall -std=c++11 str_sim.cpp
- ./a.out
复制代码 |
|