📜  穿过给定字符串表示的路径所需的总时间

📅  最后修改于: 2021-10-27 16:47:56             🧑  作者: Mango

给定一个由字符‘N’、’S’、’E’‘W’组成的字符串路径,分别表示在北、南、东和西方向上的 1 个单位移动,任务是找到完成整个行程所需的时间。从原点开始的路径,如果分别需要 2 分钟和 1 分钟才能在未访问和访问过的路段上行驶。

例子 :

方法:想法是使用一个 Set 来存储所有访问过的段,在访问每个段之前,检查它是否存在于 Set 中。请按照以下步骤解决问题。

  • 初始化一个集合s来存储一对整数。该集合将存储所有访问过的段。
  • 初始化两个整数x = 0 和y = 0 表示当前位置。此外,初始化一个变量time = 0 以存储穿越完整路径所需的总时间。
  • 遍历字符串并按照以下步骤操作
    • 将两个整数pq分别初始化为xy
    • 如果path[i]等于‘N’增加y ,否则如果path[i]等于‘S’减少y,否则如果path[i]等于‘E’增加x ,否则减少x
    • 检查段 { p + x , q + y } 是否存在于集合中。如果它确实将时间值加 1,否则将时间值加 2
    • 将段 { p + x , q + y } 插入到集合中。
  • 完成上述步骤后,打印时间

下面是上述方法的实现。

C++
// C++ code for the above approach
#include 
using namespace std;
 
// Function to calculate time
// taken to travel the path
void calcTotalTime(string path)
{
    // Stores total time
    int time = 0;
 
    // Initial position
    int x = 0, y = 0;
 
    // Stores visited segments
    set > s;
 
    for (int i = 0; i < path.size(); i++) {
 
        int p = x;
        int q = y;
 
        if (path[i] == 'N')
            y++;
 
        else if (path[i] == 'S')
            y--;
 
        else if (path[i] == 'E')
            x++;
 
        else if (path[i] == 'W')
            x--;
 
        // Check whether segment
        // is present in the set
        if (s.find({ p + x, q + y })
            == s.end()) {
            // Increment the value
            // of time by 2
            time += 2;
 
            // Insert segment into the set
            s.insert({ p + x, q + y });
        }
        else
            time += 1;
    }
 
    // Print the value
    // of time
    cout << time << endl;
}
 
// Driver Code
int main()
{
    string path = "NSE";
 
    calcTotalTime(path);
 
    return 0;
}


Java
// Java program for above approach
import java.util.*;
 
class GFG{
 
// Function to calculate time
// taken to travel the path
static void calcTotalTime(String path)
{
     
    // Stores total time
    int time = 0;
 
    // Initial position
    int x = 0, y = 0;
 
    // Stores visited segments
    Set s = new HashSet<>();
    for(int i = 0; i < path.length(); i++)
    {
        int p = x;
        int q = y;
 
        if (path.charAt(i) == 'N')
            y++;
 
        else if (path.charAt(i) == 'S')
            y--;
 
        else if (path.charAt(i) == 'E')
            x++;
 
        else if (path.charAt(i) == 'W')
            x--;
 
        // Check whether segment
        // is present in the set
        String o = (p + x) + " " + (q + y);
        if (!s.contains(o))
        {
             
            // Increment the value
            // of time by 2
            time += 2;
 
            // Insert segment into the set
            s.add(o);
        }
        else
            time += 1;
    }
 
    // Print the value
    // of time
    System.out.println(time);
}
 
// Driver Code
public static void main(String[] args)
{
    String path = "NSE";
 
    calcTotalTime(path);
}
}
 
// This code is contributed by Hritik


Python3
# Python 3 code for the above approach
 
# Function to calculate time
# taken to travel the path
def calcTotalTime(path):
 
    # Stores total time
    time = 0
 
    # Initial position
    x = 0
    y = 0
 
    # Stores visited segments
    s = set([])
 
    for i in range(len(path)):
 
        p = x
        q = y
 
        if (path[i] == 'N'):
            y += 1
 
        elif (path[i] == 'S'):
            y -= 1
 
        elif (path[i] == 'E'):
            x += 1
 
        elif (path[i] == 'W'):
            x -= 1
 
        # Check whether segment
        # is present in the set
        if (p + x, q + y) not in s:
            # Increment the value
            # of time by 2
            time += 2
 
            # Insert segment into the set
            s.add((p + x, q + y))
 
        else:
            time += 1
 
    # Print the value
    # of time
    print(time)
 
 
# Driver Code
if __name__ == "__main__":
 
    path = "NSE"
 
    calcTotalTime(path)
 
    # This code is contributed by ukasp.


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to calculate time
// taken to travel the path
static void calcTotalTime(string path)
{
     
    // Stores total time
    int time = 0;
 
    // Initial position
    int x = 0, y = 0;
 
    // Stores visited segments
    HashSet s = new HashSet();
    for(int i = 0; i < path.Length; i++)
    {
        int p = x;
        int q = y;
 
        if (path[i] == 'N')
            y++;
 
        else if (path[i] == 'S')
            y--;
 
        else if (path[i] == 'E')
            x++;
 
        else if (path[i] == 'W')
            x--;
 
        // Check whether segment
        // is present in the set
        string o = (p + x) + " " + (q + y);
        if (s.Contains(o) == false)
        {
             
            // Increment the value
            // of time by 2
            time += 2;
 
            // Insert segment into the set
            s.Add(o);
        }
        else
            time += 1;
    }
 
    // Print the value
    // of time
    Console.Write(time);
}
 
// Driver Code
public static void Main()
{
    string path = "NSE";
 
    calcTotalTime(path);
}
}
 
// This code is contributed by bgangwar59


Javascript


输出:
5

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