Class Solution
java.lang.Object
g2501_2600.s2515_shortest_distance_to_target_string_in_a_circular_array.Solution
2515 - Shortest Distance to Target String in a Circular Array.<p>Easy</p>
<p>You are given a <strong>0-indexed</strong> <strong>circular</strong> string array <code>words</code> and a string <code>target</code>. A <strong>circular array</strong> means that the array’s end connects to the array’s beginning.</p>
<ul>
<li>Formally, the next element of <code>words[i]</code> is <code>words[(i + 1) % n]</code> and the previous element of <code>words[i]</code> is <code>words[(i - 1 + n) % n]</code>, where <code>n</code> is the length of <code>words</code>.</li>
</ul>
<p>Starting from <code>startIndex</code>, you can move to either the next word or the previous word with <code>1</code> step at a time.</p>
<p>Return <em>the <strong>shortest</strong> distance needed to reach the string</em> <code>target</code>. If the string <code>target</code> does not exist in <code>words</code>, return <code>-1</code>.</p>
<p><strong>Example 1:</strong></p>
<p><strong>Input:</strong> words = [“hello”,“i”,“am”,“leetcode”,“hello”], target = “hello”, startIndex = 1</p>
<p><strong>Output:</strong> 1</p>
<p><strong>Explanation:</strong> We start from index 1 and can reach “hello” by</p>
<ul>
<li>
<p>moving 3 units to the right to reach index 4.</p>
</li>
<li>
<p>moving 2 units to the left to reach index 4.</p>
</li>
<li>
<p>moving 4 units to the right to reach index 0.</p>
</li>
<li>
<p>moving 1 unit to the left to reach index 0. The shortest distance to reach “hello” is 1.</p>
</li>
</ul>
<p><strong>Example 2:</strong></p>
<p><strong>Input:</strong> words = [“a”,“b”,“leetcode”], target = “leetcode”, startIndex = 0</p>
<p><strong>Output:</strong> 1</p>
<p><strong>Explanation:</strong> We start from index 0 and can reach “leetcode” by</p>
<ul>
<li>
<p>moving 2 units to the right to reach index 3.</p>
</li>
<li>
<p>moving 1 unit to the left to reach index 3.</p>
</li>
</ul>
<p>The shortest distance to reach “leetcode” is 1.</p>
<p><strong>Example 3:</strong></p>
<p><strong>Input:</strong> words = [“i”,“eat”,“leetcode”], target = “ate”, startIndex = 0</p>
<p><strong>Output:</strong> -1</p>
<p><strong>Explanation:</strong> Since “ate” does not exist in <code>words</code>, we return -1.</p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 100</code></li>
<li><code>1 <= words[i].length <= 100</code></li>
<li><code>words[i]</code> and <code>target</code> consist of only lowercase English letters.</li>
<li><code>0 <= startIndex < words.length</code></li>
</ul>
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionintclosetTarget(String[] words, String target, int startIndex)
-
Constructor Details
-
Solution
public Solution()
-
-
Method Details
-
closetTarget
-