Suffix and Prefix of a string. Pick up piece that serves both

Posted on

Question :

I need to do a function that returns the Length of a part of the string that is both suffix and prefix. So: Given the string: abbabba, the answer would be 4, because that would be it:


a ab abb abba abbab abbabb 


a ba bba abba babba bbabba

So abba is both a prefix and a suffix. How do I do this?

I started this way and I can not and I only have 10 more minutes.

public int teste(string nome)

            string[] pre = new string[nome.Length];
            string[] suf = new string[nome.Length];

            for (int i = 0; i < nome.Length - 1; i++)
                pre = nome[i].ToString();// Erro aqui



Answer :

I made a while that is comparing the beginning with the final until it reaches the half

String nome = "abbabba";

var i = 0; // começo
var j = nome.Length-1; // fim, -1 porque começo do 0
var tamanho = 0;
var sufixoEprefixo = "";

while (i <= j) {
    if (nome[i] == nome[j]) { // mesmo caracter
        sufixoEprefixo += nome[i];
    } else { // se for diferente pode parar 
    i++; // avança letra
    j--; // retrocede letra





IdeOne Example


I do not know how it gets in C #, but I’ll give the answer in with the logic and you can apply it in your case.

var String = "abbabba";
var len = String.length; //Aqui você terá o tamanho da sua string
var array1, array2;
var lenfinal;

    array1[i] = String.caracter(0,i);
    array2[len-i] = String.caracter(len-i,i);

//Nesse ponto você deveria ter 2 arrays(array1 e array2) com todos os prefixos e sufixos da string

para(u=0;u<len;u++) {
    if(array1[u] estacontidoem array2){
        lenfinal = array[u].length;


It’s basically this, just apply it in C # now

In this case I believe that the correct answer would be 7. Since we have a palindromo the whole word can be suffix and prefix at the same time


I do not know what the C # code looks like, but let’s go step by step:

1 Pass the string to the 2 function Declare 1 array for prefixes and 1 array for suffixes
3 Declare 1 variable to count how many prefixes are equal to
     4 suffixes fill in the array of prefixes
5 fill in the array of 6 suffixes for each element in the array of prefixes, make sure it is in the
    array of suffixes
  6 If you are, add 1 in your variable 7 and return the variable

NOTE : You will not match the vector to a string, you will add the string to the vector.


Leave a Reply

Your email address will not be published. Required fields are marked *