Skip to content

Instantly share code, notes, and snippets.

@shailrshah
Last active November 13, 2017 18:00
Show Gist options
  • Save shailrshah/b6d1f6bcb886977628af71442582e61d to your computer and use it in GitHub Desktop.
Save shailrshah/b6d1f6bcb886977628af71442582e61d to your computer and use it in GitHub Desktop.
Find out if s2 is a substring of s1
/**
* Created by shail on 4/11/17.
*/
public class Substring {
static boolean isStartsWith(int start, String s1, String s2){
int n = s2.length();
for(int i1 = start, i2 = 0; i2 < n; i1++, i2++)
if(s1.charAt(i1) != s2.charAt(i2))
return false;
return true;
}
static boolean isSubstring(String s1, String s2){
int n1 = s1.length();
int n2 = s2.length();
if(n2 == 0)
return true;
if(n2 > n1)
return false;
for(int i = 0; i < s1.length(); i++)
if(isStartsWith(i, s1, s2))
return true;
return false;
}
public int strStr(String haystack, String needle) {
for(int i = 0; ; i++)
for(int j = 0; ; j++) {
if(j == needle.length())
return i;
if((i+j) == haystack.length())
return -1;
if(haystack.charAt(i+j) != needle.charAt(j))
break;
}
}
public static void main(String args[]){
System.out.println(isSubstring("abc", "abc"));
System.out.println(isSubstring("abcd", "abc"));
System.out.println(isSubstring("qabc", "abc"));
System.out.println(isSubstring("qabcd", "abc"));
System.out.println(isSubstring("abcabcd", "abcd"));
System.out.println(isSubstring("aabcdbc", "abc"));
System.out.println(isSubstring("abcd", "abcde"));
System.out.println(isSubstring("aabcdbc", ""));
System.out.println(isSubstring("aabcdbc", "c"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment