Advertisement
Guest User

Untitled

a guest
Jul 26th, 2017
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.63 KB | None | 0 0
  1. public class Substring {
  2.     public static boolean isSubstring( String s1, String s2 ) {
  3.         // Base Case 1:  if s1 is shorter than s2 return false
  4.         if ( s1.length() < s2.length() )
  5.             return false;
  6.  
  7.         // Path 1:  s1 starts with the string s2
  8.         if ( subStringsAreEqual( s1, s2 ) )
  9.                 return true;
  10.  
  11.         // Path 2: Remove first char of s1 and see if s2 is a substring of the new s1
  12.         return isSubstring( s1.substring( 1 ), s2 );
  13.     }
  14.  
  15.     private static boolean subStringsAreEqual( String s1, String s2 ) {
  16.         // Base case 2:  if s2 length equals 0 then s2 is a substring of s1
  17.         if ( s2.length() == 0 )
  18.             return true;
  19.  
  20.                 // if the first half of the statement is false, the second half is not
  21.                 // evaluated due to the short circuiting of the && operator.
  22.         return ( s1.charAt( 0 ) == s2.charAt( 0 ) )
  23.                 // Path 2:  if first char of s1 and s2 are equal, remove first
  24.                 // char and recurse to check next char
  25.                 && subStringsAreEqual( s1.substring( 1 ), s2.substring( 1 ) );
  26.     }
  27.  
  28.     public static void main( String[] argv ) {
  29.         String s1 = "substring", s2 = "string";
  30.  
  31.         System.out.println( Substring.isSubstring( s1, s2 ) );
  32.  
  33.         s1 = "hello";
  34.         s2 = "hell";
  35.  
  36.         System.out.println( Substring.isSubstring( s1, s2 ) );
  37.  
  38.         s1 = "Madam";
  39.         s2 = "ada";
  40.  
  41.         System.out.println( Substring.isSubstring( s1, s2 ) );
  42.  
  43.         s1 = "program";
  44.         s2 = "pgram";
  45.  
  46.         System.out.println( Substring.isSubstring( s1, s2 ) );
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement