Substring algorithm

后端 未结 11 1298
小蘑菇
小蘑菇 2021-02-11 03:38

Can someone explain to me how to solve the substring problem iteratively?

The problem: given two strings S=S1S2S

11条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-11 04:08

    Not sure what language you're working in, but here's an example in C#. It's a roughly n2 algorithm, but it will get the job done.

    bool IsSubstring (string s, string t)
    {
       for (int i = 0; i <= (s.Length - t.Length); i++)
       {
          bool found = true;
    
          for (int j = 0; found && j < t.Length; j++)
          {
             if (s[i + j] != t[j])
                 found = false;
          }
    
          if (found)
             return true;
       }
    
       return false;
    }

提交回复
热议问题