Check if a string is rotation of another WITHOUT concatenating

后端 未结 11 1401
死守一世寂寞
死守一世寂寞 2020-12-25 08:11

There are 2 strings , how can we check if one is a rotated version of another ?

For Example : hello --- lohel

One simple solution is by co

11条回答
  •  眼角桃花
    2020-12-25 09:06

    Simple solution in Java. No need of iteration or concatenation.

    private static boolean isSubString(String first, String second){
            int firstIndex = second.indexOf(first.charAt(0));
            if(first.length() == second.length() && firstIndex > -1){
    
                if(first.equalsIgnoreCase(second))
                    return true;
    
                int finalPos = second.length() - firstIndex ; 
                return second.charAt(0) == first.charAt(finalPos)
                && first.substring(finalPos).equals(second.subSequence(0, firstIndex));
            }
            return false;
    
        }
    

    Test case:

    String first = "bottle";
    String second = "tlebot";
    

    Logic:

    Take the first string's first character, find the index in the second string. Subtract the length of the second with the index found, check if first character of the second at 0 is same as character at the difference of length of the second and index found and substrings between those 2 characters are the same.

提交回复
热议问题