大厂笔试题
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
1.1 KiB

2 weeks ago
2 weeks ago
2 weeks ago
  1. #include<iostream>
  2. #include<string>
  3. #include<vector>
  4. using namespace std;
  5. pair<int, string> fun(const string &str)
  6. {
  7. vector<string> substrs;
  8. int len = str.length();
  9. string substring;
  10. int maxcount(0);
  11. //后缀数组
  12. for (int i = 0; i < len; ++i)
  13. {
  14. substrs.push_back(str.substr(i));
  15. // cout << substrs[i] << endl;
  16. }
  17. for (int i = 0; i < len; ++i)
  18. {
  19. for (int j = 1; j <= len; j++) {
  20. int count = 1;
  21. int sublen = j;
  22. for (int k = i + 1; k < len; k++) {
  23. if (substrs[k].length() < sublen) {
  24. break;
  25. }
  26. string str1 = substrs[i].substr(0, sublen);
  27. string str2 = substrs[k].substr(0, sublen);
  28. if (str1.compare(str2)==0)
  29. {
  30. ++count;
  31. }
  32. }
  33. if (count > maxcount||(count == maxcount && sublen > substring.length()))
  34. {
  35. maxcount = count;
  36. substring = substrs[i].substr(0, sublen);
  37. }
  38. }
  39. }
  40. return make_pair(maxcount, substring);
  41. }
  42. int main()
  43. {
  44. string str;
  45. int len;
  46. cin >> len;
  47. cin >> str;
  48. auto res = fun(str);
  49. cout << res.first << endl;
  50. // cout << "the matched substring is:" << res.second << endl;
  51. return 0;
  52. }