How to find the longest border of a string?
💻 coding

How to find the longest border of a string?

1 min read 174 words
1 min read
ShareWhatsAppPost on X
  • 1A border of a string is a substring that is both a proper prefix and proper suffix.
  • 2The longest border of the string 'abcdabc' is 'abc' with a length of 3.
  • 3The provided C++ algorithm efficiently calculates the longest border with a time complexity of O(n).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"A border of a string is a substring that is both a proper prefix and proper suffix."

How to find the longest border of a string?

The border of a string is a substring which is both a proper prefix and proper suffix of the string — "proper" meaning that the whole string does not count as a substring. The longest border of x is "ab". The longest border of y is "abab" (the prefix and suffix can overlap).

More details can be found at the link: https://en.wikipedia.org/wiki/Substring#Border

e.g

abcdabc - border string is abc - length is 3

ababab - border string is abab - length is 4

C++ solution/ Algorithm for border string is as below.

#include <string>
#include <vector>
#include <iostream>

using namespace std;

int longestBorder(const string& s) {
	int len = s.length();
	vector<int> prefixFunc(len); 
	prefixFunc[0] = 0;
 	 
	int curBorderLen = 0;	
	for (int i = 1; i < len; ++i) {	
		while (curBorderLen > 0 && s[curBorderLen] != s[i]) 
			curBorderLen = prefixFunc[curBorderLen - 1]; 
		 
		if (s[curBorderLen] == s[i]) 
 ++curBorderLen;
 
 		prefixFunc[i] = curBorderLen;
 	}

 	return prefixFunc[len-1];
}

int main() {
	string s;
	cin >> s;
	cout << longestBorder(s) << endl;
}

Time Complexity: O(n)

Ideone - https://ideone.com/UIjwSG

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 1 September 2018 · 1 min read · 174 words

Part of AskGif Blog · coding

You might also like

How to find the longest border of a string? | AskGif Blog