Monday 12 October 2015

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, and
s1 = WXYZ, and s2 = XWYZ, return false.

Solution # 1

     public static boolean checkRotational(String str1, String str2) {
           int length = str1.length();
           if(length!=str2.length()) {
                return false;
           } else if(str1.equals(str2)) {
                return true;
           }
           for(int i=1;i<length;i++) {
                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) {
           str1 = str1+str1;
           if(str1.contains(str2)) {
                return true;
           } else {
                return false;
           }
     }

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...