📌  相关文章
📜  在跟随给定字符串指定的路径时重新访问的计数点

📅  最后修改于: 2021-09-06 17:46:25             🧑  作者: Mango

给定一个表示一系列移动( LRUD )的字符串S和表示起始坐标的两个整数XY ,任务是找到在遵循给定方向指定的方向时重新访问的位置数字符串按照以下规则:

  • 如果当前字符是L ,则将x坐标减1
  • 如果当前字符是R ,则将x坐标增加1
  • 如果当前字符是U ,则将y坐标增加1
  • 如果当前字符是D ,则将y坐标减1

例子:

方法:按照给定的步骤解决问题:

  • 初始化一个 HashSet 对,用于存储在遍历给定字符串访问的坐标对和 HashSet 中的当前坐标。
  • 遍历给定的字符串S并执行以下步骤:
    • 根据给定的规则更新坐标{X, Y}的值。
    • 检查更新的坐标是否存在于 HashSet 中。如果发现为true ,则将count增加1 。否则,继续。
  • 完成上述步骤后,打印计数的值作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find the number of times
// already visited position is revisited
// after starting traversal from {X, Y}
int count(string S, int X, int Y)
{
    int N = S.length();
 
    // Stores the x and y temporarily
    int temp_x = 0, temp_y = 0;
 
    // Stores the number of times an
    // already visited position
    // is revisited
    int count = 0;
 
    // Initialize hashset
    set > s;
 
    // Insert the starting coordinates
    s.insert({ X, Y });
 
    // Traverse over the string
    for (int i = 0; i < N; i++) {
        temp_x = X;
        temp_y = Y;
 
        // Update the coordinates according
        // to the current directions
        if (S[i] == 'U') {
            X++;
        }
        else if (S[i] == 'D') {
            X--;
        }
        else if (S[i] == 'R') {
            Y++;
        }
        else {
            Y--;
        }
 
        // If the new {X, Y} has been
        // visited before, then
        // increment the count by 1
        if (s.find({ temp_x + X, temp_y + Y })
            != s.end()) {
            count++;
        }
 
        // Otherwise
        else {
 
            // Insert new {x, y}
            s.insert({ temp_x + X,
                       temp_y + Y });
        }
    }
 
    return count;
}
 
// Driver Code
int main()
{
    string S = "RDDUDL";
    int X = 0, Y = 0;
    cout << count(S, X, Y);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG
{
 
  // Function to find the number of times
  // already visited position is revisited
  // after starting traversal from {X, Y}
  static int count(String S, int X, int Y)
  {
    int N = S.length();
 
    // Stores the x and y temporarily
    int temp_x = 0, temp_y = 0;
 
    // Stores the number of times an
    // already visited position
    // is revisited
    int count = 0;
 
    // Initialize hashset
    HashSet s = new HashSet<>();
 
    // Insert the starting coordinates
    s.add((X + "#" + Y));
 
    // Traverse over the string
    for (int i = 0; i < N; i++) {
      temp_x = X;
      temp_y = Y;
 
      // Update the coordinates according
      // to the current directions
      if (S.charAt(i) == 'U') {
        X++;
      }
      else if (S.charAt(i) == 'D') {
        X--;
      }
      else if (S.charAt(i) == 'R') {
        Y++;
      }
      else {
        Y--;
      }
 
      // If the new {X, Y} has been
      // visited before, then
      // increment the count by 1
      if (s.contains((temp_x + X) + "#"
                     + (temp_y + Y))) {
        count++;
      }
 
      // Otherwise
      else {
 
        // Insert new {x, y}
        s.add((temp_x + X) + "#" + (temp_y + Y));
      }
    }
 
    return count;
  }
 
  // Driver Code
  public static void main(String[] args)
  {
 
    String S = "RDDUDL";
    int X = 0, Y = 0;
    System.out.print(count(S, X, Y));
  }
}
 
// This code is contributed by Kingash.


Python3
# Python3 program for the above approach
 
# Function to find the number of times
# already visited position is revisited
# after starting traversal from {X, Y}
def count(S, X, Y):
    N = len(S)
 
    # Stores the x and y temporarily
    temp_x, temp_y = 0, 0
 
    # Stores the number of times an
    # already visited position
    # is revisited
    count = 0
 
    # Initialize hashset
    s = {}
 
    # Insert the starting coordinates
    s[(X, Y)] = 1
 
    # Traverse over the string
    for i in range(N):
        temp_x = X
        temp_y = Y
 
        # Update the coordinates according
        # to the current directions
        if (S[i] == 'U'):
            X += 1
        elif (S[i] == 'D'):
            X -= 1
        elif (S[i] == 'R'):
            Y += 1
        else:
            Y -= 1
 
        # If the new {X, Y} has been
        # visited before, then
        # increment the count by 1
        if ((temp_x + X, temp_y + Y ) in s):
            count += 1
        # Otherwise
        else:
            # Insert new {x, y}
            s[(temp_x + X,temp_y + Y )] = 1
    return count
 
# Driver Code
if __name__ == '__main__':
    S = "RDDUDL"
    X,Y = 0, 0
    print (count(S, X, Y))
 
    # This code is contributed by mohit kumar 29.


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
public class GFG
{
 
  // Function to find the number of times
  // already visited position is revisited
  // after starting traversal from {X, Y}
  static int count(String S, int X, int Y)
  {
    int N = S.Length;
 
    // Stores the x and y temporarily
    int temp_x = 0, temp_y = 0;
 
    // Stores the number of times an
    // already visited position
    // is revisited
    int count = 0;
 
    // Initialize hashset
    HashSet s = new HashSet();
 
    // Insert the starting coordinates
    s.Add((X + "#" + Y));
 
    // Traverse over the string
    for (int i = 0; i < N; i++) {
      temp_x = X;
      temp_y = Y;
 
      // Update the coordinates according
      // to the current directions
      if (S[i] == 'U') {
        X++;
      }
      else if (S[i] == 'D') {
        X--;
      }
      else if (S[i] == 'R') {
        Y++;
      }
      else {
        Y--;
      }
 
      // If the new {X, Y} has been
      // visited before, then
      // increment the count by 1
      if (s.Contains((temp_x + X) + "#"
                     + (temp_y + Y))) {
        count++;
      }
 
      // Otherwise
      else {
 
        // Insert new {x, y}
        s.Add((temp_x + X) + "#" + (temp_y + Y));
      }
    }
    return count;
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    String S = "RDDUDL";
    int X = 0, Y = 0;
    Console.Write(count(S, X, Y));
  }
}
 
// This code is contributed by Amit Katiyar


Javascript


输出:
2

时间复杂度: O(N*log N)
辅助空间: O(N)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live