CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: Strings

  1. #1
    Join Date
    Jan 2009
    Posts
    5

    Strings

    x1, x2 are two strings. you should find what is the length of the largest substring of x2 containing only letters from x1. For example: if x1="abc" and x2="cvbaacdab" the answer will be 4 because "baac" is the largest substring.
    can you help me find a recursive way (no loops please) to find the answer?

  2. #2
    Join Date
    Apr 2007
    Posts
    442

    Re: Strings

    Sound like a school assignment, to get help on those, much better to show some effort, ask specific questions on whatever issues you are stuck with.

    Just posting the assignment, does not really give anything to help or comment on, does it? So be more specific, on what you are having difficulty with, recursion, String comparison or what?

  3. #3
    Join Date
    Jan 2009
    Posts
    5

    Re: Strings

    it is not an assignment but a trial to teach myself java.
    I found this question but didn't find the answer.. I know how to find the longest substring if it starts at the end of x2 using indexOf and charAt and substring but don't find a way to do it if it somewhere else.

  4. #4
    Join Date
    Nov 2003
    Posts
    1,405

    Re: Strings

    Quote Originally Posted by mat65 View Post
    x1, x2 are two strings. you should find what is the length of the largest substring of x2 containing only letters from x1. For example: if x1="abc" and x2="cvbaacdab" the answer will be 4 because "baac" is the largest substring.
    can you help me find a recursive way (no loops please) to find the answer?
    It's quite easy to turn iteration into recursion. Instead of returning to the beginning of a loop for another iteration, the recursive method calls itself, like

    Code:
    void loop(int N) { // iteration
       for (int i=0; i<N; i++) {
          // do
       }
    }
    //
    void rec(int i, int N) { // equivalent recursion
       if (i<N) {
          // do
          rec(i+1, N); // next "iteration"
       }
    }
    So if you have an iterative solution strategy ready, its quite straightforward to turn it into recursion.

    The above is called "tail" recursion and isn't very elegant. If you want to secure an A you should use a divide-and-conquer approach instead.
    Last edited by _uj; January 20th, 2009 at 01:51 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured