算法,寻找单一子串

  • Post author:
  • Post category:其他


从一个长串中找出没有相同字符的最长子串。

int find_length(std::string temp,char c)

{


printf(“temp %s,%c.\n”,temp.c_str(),c);

int length = temp.length();

for(int i = 0;i<temp.length();i++)

{


if(temp[i] == c)

{


return temp.length();

if(temp.length() – i > i)

{


return temp.length() – i;

}

else

{


return i;

}

}

}

return -1;

}

int GetLongestSignelString(std::string value)

{


std::string temp;

int max_count = 0;

for(int i = 0;i<value.length();i++)

for(int j = i + 1;j<value.length();j++)

{


temp = value.substr(i,j-i);

int found_len = find_length(temp,value[j]);

printf(” found_len %d.############ i %d j %d len %d\n”,found_len,i,j,temp.length());

if(found_len > 0)

{


if(found_len > max_count)

{


max_count = found_len;

}

printf(“break 11.max_count %d\n”,max_count);

break;

}

else

{


if(j == value.length() – 1)

{


if(temp.length() + 1 > max_count)

{


max_count = temp.length() + 1;

}

printf(“break here.max_count %d\n”,max_count);

break;

}

printf(“break 22.\n”);

}

}

return max_count;

}

int main()

{


std::string str(“accbjhbsaalkbsdwie12324326492!@#%$&^*VMYHG”);

printf(“longest %d.\n”,GetLongestSignelString(str));

return 0;

}

最近优化了一个高效一些的版本。

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#include <string>

#include <vector>

#include <iostream>

int findLast(char* a, int len, char c)

{


if (len == 0) {


return 0;

}

for (int i = len – 1; i >= 0;i –)

if (a[i] == c) {


return i + 1;

}

return 0;

}

std::string SingleStr(const std::string& str)

{


int validlen = 0;

std::string result;

char *bufstr = (char*)malloc(str.length());

for (int i = 0; i<str.length(); i++)

{


int find = findLast(bufstr, validlen, str[i]);

if (find != 0) {


if (find > result.length()) {


result.assign(bufstr, find);

}

memmove(bufstr, bufstr + find, validlen – find);

validlen -= find;

}

bufstr[validlen ++] = str[i];

if (validlen > result.length()) {


result.assign(bufstr, validlen);

}

}

if (validlen > result.length()) {


result.assign(bufstr, validlen);

}

free(bufstr);

return result;

}


int main()

{


std::string a(“120135435”);

std::cout<<SingleStr(a)<<std::endl;

}

以上使用的是蛮力比的过程输出,不过效率不高,比较耗时



版权声明:本文为fantasy_ARM9原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。