Monday, 25 April 2016

Check whether two strings are rotational equal or not


Check whether two strings are rotational equal or not 

(rotations of each other or not)

Given a string s1 and a string s2, check whether s2 is a rotation of s1
s1 = WXYZ and s2 = YZWX, return true
s1 = WXYZ, and s2 = XWYZ, return false

Solution # 1


public static boolean checkRotational(String str1, String str2) {
     int length = str1.length();

     // Check if both strings are of equal size
     // Check if both strings are exactly equal
     if (length != str2.length()) {
        return false;
     } else if (str1.equals(str2)) {
        return true;
     }

     // Manipulate first string and match with other one
     // Take one char of string and rest of string, Join s2+s1
     for(int i=1; i<lengthi++) {
        String s1 = str1.substring(0,1);
        String s2 = str1.substring(1, length);
        str1 = s2+s1;
        if(str2.equals(str1)) {
           return true;
        }
      }
     
     return false;
}


Best Solution # 2

static boolean checkRotational(String str1, String str2) {
     // Add string 1 two times into str1
     str1 = str1+str1;

     // Check if str1 contains other string
     if(str1.contains(str2)) {
         return true;
     } else {
         return false;
     }
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.