牛骨文教育服务平台(让学习变的简单)
博文笔记

求字符串中最长连续递增子数字串

创建时间:2012-10-17 投稿人: 浏览次数:2101

求字符串中最长连续递增子数字串
例:输入串为a23b6489wci6782345xy,则输出为2345
注意,只需要考虑一位数,所以对任意字符串,最长可能的输出为0123456789.

 

我的算法:

BOOL FindSub(const char pStr[], int nLen, int &StartIndex, int &EndIndex)
{
 // 对传入值进行初始化
 StartIndex = -1;
 EndIndex = -1;

 int nStartNum = -1, nPreNumIndex = -1, nPreNum=-1, nCurNum = -1;
 for(int i=0; i<nLen; i++)
 {
  if(pStr[i] >= "0" && pStr[i] <= "9")  // 为数字
  {
   nCurNum = pStr[i];
   if(StartIndex == -1) // 负初值
   {
    StartIndex = i;
    EndIndex = i;
   }

   if(nStartNum == -1)   // 新的数字开始了
   {
    nStartNum = i;
   }
   else
   {
    if(nPreNumIndex == i-1)   // 上一个也为数字,
    {
     if(nCurNum > nPreNum) // 并且当前值比前一个大
     {
      if(i - nStartNum > EndIndex - StartIndex)
      {
       StartIndex = nStartNum;
       EndIndex = i;
      }
     }
     else
     { 
      // 重新开始计数
      nStartNum = i;
     }
    }
   }

   // 迭代更新
   nPreNumIndex = i;
   nPreNum = nCurNum;
  }
  else
  {
   nStartNum = -1;
  }
 }// for i end

 return TRUE;
}

 

声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。