int (CharSequence leafText, CharSequence pattern, int patternIndex, int finalPatternIndex, int direction) { int leafIndex = direction == 1 ? 0 : leafText.length() - 1; int finalLeafIndex = direction == 1 ? leafText.length() - 1 : 0; int result = 0; while (leafText.charAt(leafIndex) == pattern.charAt(patternIndex)) { result++; if (leafIndex == finalLeafIndex || patternIndex == finalPatternIndex) { break; } leafIndex += direction; patternIndex += direction; } return result; }