2015-09-27 4 views
2

Как вернуть индекс d в следующую строку "abbcccddddcccbba" Я знаю, как найти самую длинную подстроку, но поиск начального индекса ускользает от меня.Индекс возврата самой длинной подстроки

public static int IndexOfLongestRun(string str) 
    { 
     int currentIndex = 0; 

     int finalIndex = 0; 

     int longestOccurence = 0; 

     for (int i = 0; i < str.Length - 1; i++) 
     { 
      if (str[i] == str[i + 1]) 
      { 
       currentIndex++; 
      } 

      else 
      { 
       currentIndex = 1; 
      } 

      if (longestOccurence < currentIndex) 
      { 
       longestOccurence = currentIndex; 
      } 
     } 


     return str.IndexOf(str, longestOccurence); // return what??? 
    } 

ответ

4

Я проверил следующее, и я думаю, что это самый эффективный способ:

public static int IndexOfLongestRun(string str) 
{ 
    if (string.IsNullOrEmpty(str)) return -1; 

    int currentStartIndex = 0; 
    int longestIndex = 0; 
    int longestLength = 0; 
    int currentLenght = 0; 

    for (int i = 0; i < str.Length - 1; i++) 
    { 
    if (str[i] != str[i + 1]) 
    { 
     currentStartIndex = i + 1; 
     currentLenght = 1; 
    } 
    else 
    { 
     currentLenght++; 
    } 

    if (currentLenght > longestLength) 
    { 
     longestLength = currentLenght; 
     longestIndex = currentStartIndex; 
    } 
    } 

    return longestIndex; 
} 
+1

Я полагаю, 'longestIndex' начальное значение должно быть' -1' в случае строка пустая –

+0

будет редактировать мой ансер. Я бы предпочел вернуть -1 сразу, когда обнаружил, что строка является пустой или пустой. – KOTIX

Смежные вопросы