Created
January 13, 2014 18:21
-
-
Save naveenwashere/8405312 to your computer and use it in GitHub Desktop.
Assume you have a method isSubstring which checks if one word is a substring of another. Given two string s1 and s2, write code to check if s2 is a roatation of sq using only one call ot isSubstring (eg., "waterbottle" is a rotation of "erbottlewat").
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.interview.coding.crack; | |
public class FindingIfSubstring { | |
public boolean isSubstring(char a[], char b[]) | |
{ | |
int joint = 0; | |
int indexer = 0; | |
boolean flag = false; | |
if(a.length != b.length) | |
return false; | |
/* | |
char[] a = {'w','a','t','e','r','b','o','t','t','l','e'}; | |
char[] b = {'e','r','b','o','t','t','l','e','w','a','t'}; | |
char[] c = {'e','a','t','e','r','b','o','t','t','l','e'}; | |
char[] d = {'e','r','b','o','t','t','l','e','e','a','t'}; | |
*/ | |
/* | |
* First track the index at which the string is rotated | |
*/ | |
for(int i = 0; i < a.length; i++) | |
{ | |
if(a[i] != b[indexer]) | |
{ | |
joint = i+1; | |
} | |
else | |
{ | |
indexer++; | |
} | |
} | |
System.out.println("Rotated at index " + joint); | |
/* | |
* Start from the beginning of roatation index of the 1st string and the end of of the | |
* 2nd string. Find of all the characters till the beginning of 1st string, match. | |
*/ | |
indexer = joint - 1; | |
int len = b.length; | |
for(int i = 0; i < joint; i++) | |
{ | |
if(a[indexer] == b[len - 1 - i]) | |
flag = true; | |
else | |
flag = false; | |
indexer--; | |
} | |
return flag; | |
} | |
/** | |
* @param args | |
*/ | |
public static void main(String[] args) { | |
char[] a = {'w','a','t','e','r','b','o','t','t','l','e'}; | |
char[] b = {'e','r','b','o','t','t','l','e','w','a','t'}; | |
char[] c = {'e','a','t','e','r','b','o','t','t','l','e'}; | |
char[] d = {'e','r','b','o','t','t','l','e','e','a','t'}; | |
FindingIfSubstring fis = new FindingIfSubstring(); | |
if(fis.isSubstring(a, b)) | |
System.out.println("Yes, " + a + " and "+ b + " are substrings"); | |
else | |
System.out.println("Nope, " + a.toString() + " and "+ b.toString() + " are not substrings"); | |
if(fis.isSubstring(a, c)) | |
System.out.println("Yes, " + a.toString() + " and "+ b.toString() + " are substrings"); | |
else | |
System.out.println("Nope, " + a.toString() + " and "+ b.toString() + " are not substrings"); | |
if(fis.isSubstring(c, d)) | |
System.out.println("Yes, " + a.toString() + " and "+ b.toString() + " are substrings"); | |
else | |
System.out.println("Nope, " + a.toString() + " and "+ b.toString() + " are not substrings"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment