Saturday, December 9, 2023
HomeSoftware EngineeringLearn how to Calculate String Rotation in Java

Learn how to Calculate String Rotation in Java


The problem

Write a operate that receives two strings and returns n, the place n is the same as the variety of characters we should always shift the primary string ahead to match the second. The examine needs to be case-sensitive.

As an illustration, take the strings “fatigue” and “tiguefa”. On this case, the primary string has been rotated 5 characters ahead to supply the second string, so 5 can be returned. If the second string isn’t a sound rotation of the primary string, the tactic returns -1.

Examples:

"espresso", "eecoff" => 2
"eecoff", "espresso" => 4
"moose", "Moose" => -1
"is not", "'tisn" => 2
"Esham", "Esham" => 0
"canine", "god" => -1

The answer in Java code

Choice 1:

public class CalculateRotation {
  static int shiftedDiff(String first, String second){
    if (first.size() != second.size()) return -1;
    return (second + second).indexOf(first);
  }
}

Choice 2:

public class CalculateRotation {
  static int shiftedDiff(String first, String second) {
    return (first.size() <= second.size()) ?
           (second + second).indexOf(first) : -1;
  }
}

Choice 3:

public class CalculateRotation {
   static int shiftedDiff(String first, String second){
        for (int i = 0; i <= first.size(); i++) {
            if (second.equals(first)) return i;
            first = shift(first);
        }
        return -1;
    }

    non-public static String shift(String phrase) {
        return phrase.substring(phrase.size() - 1) + phrase.substring(0, phrase.size() - 1);
    }
}

Check circumstances to validate our answer

import org.junit.Check;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

public class RotationTest {
    @Check
    public void take a look at() {
      assertEquals(-1, CalculateRotation.shiftedDiff("hoop","pooh"));
      assertEquals(2, CalculateRotation.shiftedDiff("espresso","eecoff"));
      assertEquals(4, CalculateRotation.shiftedDiff("eecoff","espresso"));
    }
}
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments