📌  相关文章
📜  用于查询给定字符串在恒定时间内的旋转和第 K 个字符的Java程序

📅  最后修改于: 2022-05-13 01:55:02.331000             🧑  作者: Mango

用于查询给定字符串在恒定时间内的旋转和第 K 个字符的Java程序

给定字符串str ,任务是对给定字符串执行以下类型的查询:

  1. (1, K):将字符串左旋转K个字符。
  2. (2, K):打印字符串的第 K字符。

例子:

方法:这里的主要观察是字符串不需要在每个查询中旋转,而是我们可以创建一个指针ptr指向字符串的第一个字符,并且可以在每次旋转时更新它ptr = (ptr + K ) %N其中K是字符串需要旋转的整数, N是字符串的长度。现在对于第二种类型的每个查询,可以通过str[(ptr + K – 1) % N]找到第 K字符。
下面是上述方法的实现:

Java
// Java implementation of the above approach
import java.util.*;
class GFG 
{
static int size = 2;
  
// Function to perform the required
// queries on the given string
static void performQueries(String str, int n,
                           int queries[][], int q)
{
  
    // Pointer pointing to the current 
    // starting character of the string
    int ptr = 0;
  
    // For every query
    for (int i = 0; i < q; i++) 
    {
  
        // If the query is to rotate the string
        if (queries[i][0] == 1)
        {
  
            // Update the pointer pointing to the
            // starting character of the string
            ptr = (ptr + queries[i][1]) % n;
        }
        else 
        {
            int k = queries[i][1];
  
            // Index of the kth character in the
            // current rotation of the string
            int index = (ptr + k - 1) % n;
  
            // Print the kth character
            System.out.println(str.charAt(index));
        }
    }
}
  
// Driver code
public static void main(String[] args)
{
    String str = "abcdefgh";
    int n = str.length();
  
    int queries[][] = { { 1, 2 }, { 2, 2 }, 
                        { 1, 4 }, { 2, 7 } };
    int q = queries.length;
  
    performQueries(str, n, queries, q);
}
} 
  
// This code is contributed by 29AjayKumar


输出:
d
e

有关详细信息,请参阅关于给定字符串的旋转和第 K 个字符的查询的完整文章!