Given a string
Return
path
, where path[i] = 'N'
, 'S'
, 'E'
or 'W'
, each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0)
on a 2D plane and walk on the path specified by path
.Return
True
if the path crosses itself at any point, that is, if at any time you are on a location you've previously visited. Return false otherwise.Example 1:
Input: path = "NESWW"
Output: true
Approach
Java
import java.util.HashSet;import java.util.Set;public class PathCrossing {public static void main(String[] args) {String path = "NESWW";System.out.println(isPathCrossing(path));}static boolean isPathCrossing(String s) {Set<Pair> st = new HashSet<>();int n = s.length();st.add(new Pair(0, 0));int x = 0, y = 0;int flag = 0;for (int i = 0; i < n; i++) {if (s.charAt(i) == 'N') {y++;int len = st.size();st.add(new Pair(x, y));if (st.size() == len) {flag = 1;break;}} else if (s.charAt(i) == 'S') {y--;int len = st.size();st.add(new Pair(x, y));if (st.size() == len) {flag = 1;break;}} else if (s.charAt(i) == 'E') {x++;int len = st.size();st.add(new Pair(x, y));if (st.size() == len) {flag = 1;break;}} else {x--;int len = st.size();st.add(new Pair(x, y));if (st.size() == len) {flag = 1;break;}}}if (flag == 1)return true;return false;}static class Pair {private int first;private int second;public Pair(int first, int second) {super();this.first = first;this.second = second;}public int getFirst() {return first;}public void setFirst(int first) {this.first = first;}public int getSecond() {return second;}public void setSecond(int second) {this.second = second;}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + first;result = prime * result + second;return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Pair other = (Pair) obj;if (first != other.first)return false;if (second != other.second)return false;return true;}}}
C++
#include <bits/stdc++.h>using namespace std;bool isPathCrossing(string s){set<pair<int, int>> st;int n = s.size();st.insert(make_pair(0, 0));int x = 0, y = 0;int flag = 0;for (int i = 0; i < n; i++){if (s[i] == 'N'){y++;int len = st.size();st.insert(make_pair(x, y));if (st.size() == len){flag = 1;break;}}else if (s[i] == 'S'){y--;int len = st.size();st.insert(make_pair(x, y));if (st.size() == len){flag = 1;break;}}else if (s[i] == 'E'){x++;int len = st.size();st.insert(make_pair(x, y));if (st.size() == len){flag = 1;break;}}else{x--;int len = st.size();st.insert(make_pair(x, y));if (st.size() == len){flag = 1;break;}}}if (flag == 1)return true;return false;}int main(){string path = "NESWW";if (isPathCrossing(path))cout << "true";elsecout << "false";return 0;}
No comments:
Post a Comment