Leetcode Solutions (161 Part Series)
1 Solution: Next Permutation
2 Solution: Trim a Binary Search Tree
… 157 more parts…
3 Leetcode Solutions Index
4 Solution: Minimize Deviation in Array
5 Solution: Vertical Order Traversal of a Binary Tree
6 Solution: Count Ways to Make Array With Product
7 Solution: Smallest String With A Given Numeric Value
8 Solution: Linked List Cycle
9 Solution: Path With Minimum Effort
10 Solution: Concatenation of Consecutive Binary Numbers
11 Solution: Minimum Operations to Make a Subsequence
12 Solution: Longest Harmonious Subsequence
13 Solution: Simplify Path
14 Solution: Building Boxes
15 Solution: Decode XORed Permutation
16 Solution: Binary Tree Right Side View
17 Solution: Find Kth Largest XOR Coordinate Value
18 Solution: Change Minimum Characters to Satisfy One of Three Conditions
19 Solution: Shortest Distance to a Character
20 Solution: Peeking Iterator
21 Solution: Convert BST to Greater Tree
22 Solution: Copy List with Random Pointer
23 Solution: Valid Anagram
24 Solution: Number of Steps to Reduce a Number to Zero
25 Solution: Shortest Path in Binary Matrix
26 Solution: Is Graph Bipartite?
27 Solution: Maximum Score From Removing Substrings (ver. 1)
28 Solution: Maximum Score From Removing Substrings (ver. 2)
29 Solution: Sort the Matrix Diagonally
30 Solution: The K Weakest Rows in a Matrix (ver. 1)
31 Solution: The K Weakest Rows in a Matrix (ver. 2)
32 Solution: Letter Case Permutation
33 Solution: Container With Most Water
34 Solution: Arithmetic Slices
35 Solution: Minimum Remove to Make Valid Parentheses
36 Solution: Roman to Integer
37 Solution: Broken Calculator
38 Solution: Find the Most Competitive Subsequence
39 Solution: Longest Word in Dictionary through Deleting
40 Solution: Search a 2D Matrix II
41 Solution: Score of Parentheses
42 Solution: Shortest Unsorted Continuous Subarray
43 Solution: Validate Stack Sequences
44 Solution: Divide Two Integers (ver. 1)
45 Solution: Divide Two Integers (ver. 2)
46 Solution: Maximum Frequency Stack
47 Solution: Distribute Candies
48 Solution: Set Mismatch (ver. 1)
49 Solution: Set Mismatch (ver. 2)
50 Solution: Missing Number
51 Solution: Intersection of Two Linked Lists
52 Solution: Average of Levels in Binary Tree
53 Solution: Short Encoding of Words (ver. 1)
54 Solution: Design HashMap (ver. 1)
55 Solution: Short Encoding of Words (ver. 2)
56 Solution: Design HashMap (ver. 2)
57 Solution: Remove Palindromic Subsequences
58 Solution: Add One Row to Tree
59 Solution: Integer to Roman
60 Solution: Coin Change
61 Solution: Check If a String Contains All Binary Codes of Size K
62 Solution: Binary Trees With Factors
63 Solution: Swapping Nodes in a Linked List
64 Solution: Encode and Decode TinyURL
65 Solution: Best Time to Buy and Sell Stock with Transaction Fee
66 Solution: Generate Random Point in a Circle
67 Solution: Wiggle Subsequence
68 Solution: Keys and Rooms
69 Solution: Design Underground System
70 Solution: Reordered Power of 2
71 Solution: Vowel Spellchecker
72 Solution: 3Sum With Multiplicity
73 Solution: Advantage Shuffle
74 Solution: Pacific Atlantic Water Flow
75 Solution: Word Subsets
76 Solution: Palindromic Substrings
77 Solution: Reconstruct Original Digits from English
78 Solution: Flip Binary Tree To Match Preorder Traversal
79 Solution: Russian Doll Envelopes
80 Solution: Stamping The Sequence
81 Solution: Palindrome Linked List
82 Solution: Ones and Zeroes
83 Solution: Longest Valid Parentheses
84 Solution: Design Circular Queue
85 Solution: Global and Local Inversions
86 Solution: Minimum Operations to Make Array Equal
87 Solution: Determine if String Halves Are Alike
88 Solution: Letter Combinations of a Phone Number
89 Solution: Verifying an Alien Dictionary
90 Solution: Longest Increasing Path in a Matrix
91 Solution: Deepest Leaves Sum
92 Solution: Beautiful Arrangement II
93 Solution: Flatten Nested List Iterator
94 Solution: Partition List
95 Solution: Fibonacci Number
96 Solution: Remove All Adjacent Duplicates in String II
97 Solution: Number of Submatrices That Sum to Target
98 Solution: Remove Nth Node From End of List
99 Solution: Combination Sum IV
100 Solution: N-ary Tree Preorder Traversal
101 Solution: Triangle
102 Solution: Brick Wall
103 Solution: Count Binary Substrings
104 Solution: Critical Connections in a Network
105 Solution: Rotate Image
106 Solution: Furthest Building You Can Reach
107 Solution: Power of Three
108 Solution: Unique Paths II
109 Solution: Find First and Last Position of Element in Sorted Array
110 Solution: Powerful Integers
111 Solution: Prefix and Suffix Search
112 Solution: Course Schedule III
113 Solution: Running Sum of 1d Array
114 Solution: Non-decreasing Array
115 Solution: Jump Game II
116 Solution: Convert Sorted List to Binary Search Tree
117 Solution: Delete Operation for Two Strings
118 Solution: Super Palindromes
119 Solution: Construct Target Array With Multiple Sums
120 Solution: Count Primes
121 Solution: Maximum Points You Can Obtain from Cards
122 Solution: Range Sum Query 2D – Immutable
123 Solution: Ambiguous Coordinates
124 Solution: Flatten Binary Tree to Linked List
125 Solution: Valid Number
126 Solution: Binary Tree Cameras
127 Solution: Longest String Chain
128 Solution: Find Duplicate File in System
129 Solution: Minimum Moves to Equal Array Elements II
130 Solution: Binary Tree Level Order Traversal
131 Solution: Find and Replace Pattern
132 Solution: N-Queens
133 Solution: To Lower Case
134 Solution: Evaluate Reverse Polish Notation
135 Solution: Partitioning Into Minimum Number Of Deci-Binary Numbers
136 Solution: Maximum Product of Word Lengths
137 Solution: Maximum Erasure Value
138 Solution: N-Queens II
139 Solution: Maximum Gap
140 Solution: Search Suggestions System
141 Solution: Max Area of Island
142 Solution: Interleaving String
143 Solution: Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
144 Solution: Open the Lock
145 Solution: Maximum Performance of a Team
146 Solution: Longest Consecutive Sequence
147 Solution: Min Cost Climbing Stairs
148 Solution: Construct Binary Tree from Preorder and Inorder Traversal
149 Solution: Jump Game VI
150 Solution: My Calendar I
151 Solution: Stone Game VII
152 Solution: Minimum Number of Refueling Stops
153 Solution: Palindrome Pairs
154 Solution: Maximum Units on a Truck
155 Solution: Matchsticks to Square
156 Solution: Generate Parentheses
157 Solution: Number of Subarrays with Bounded Maximum
158 Solution: Swim in Rising Water
159 Solution: Pascal’s Triangle
160 Solution: Out of Boundary Paths
161 Solution: Redundant Connection
This is part of a series of Leetcode solution explanations (index). If you liked this solution or found it useful, please like this post and/or upvote my solution post on Leetcode’s forums.
Leetcode Problem #816 (Medium): Ambiguous Coordinates
Description:
(Jump to: Solution Idea || Code: JavaScript | Python | Java | C++)
We had some 2-dimensional coordinates, like
"(1, 3)"
or"(2, 0.5)"
. Then, we removed all commas, decimal points, and spaces, and ended up with the strings
. Return a list of strings representing all possibilities for what our original coordinates could have been.Our original representation never had extraneous zeroes, so we never started with numbers like
"00"
,"0.0"
,"0.00"
,"1.0"
,"001"
,"00.01"
, or any other number that can be represented with less digits. Also, a decimal point within a number never occurs without at least one digit occuring before it, so we never started with numbers like".1"
.The final answer list can be returned in any order. Also note that all coordinates in the final answer have exactly one space between them (occurring after the comma.)
Examples:
Example 1: Input: s = “(123)” Output: [“(1, 23)”, “(12, 3)”, “(1.2, 3)”, “(1, 2.3)”]
Example 2: Input: s = “(00011)” Output: [“(0.001, 1)”, “(0, 0.011)”] Explanation: 0.0, 00, 0001 or 00.01 are not allowed.
Example 3: Input: s = “(0123)” Output: [“(0, 123)”, “(0, 12.3)”, “(0, 1.23)”, “(0.1, 23)”, “(0.1, 2.3)”, “(0.12, 3)”]
Example 4: Input: s = “(100)” Output: [(10, 0)] Explanation: 1.0 is not allowed.
Constraints:
4 <= s.length <= 12
s[0] = "("
,s[s.length - 1] = ")"
, and the other elements ins
are digits.
Idea:
(Jump to: Problem Description || Code: JavaScript | Python | Java | C++)
For this problem, we have two basic challenges. The first challenge is preventing invalid coordinates. For that, we can define a helper function (parse) which will take a string (str) and only pass on valid options for another helper (process) to handle.
We can break down the options into three categories:
- No decimal: Any option except one with more than 1 digit and a leading “0”.
- Decimal after first digit: Any option with more than 1 digit and no trailing “0”.
- Decimals throughout: Any option that doesn’t start and end with a “0”
After defining our first helper function, the next thing we should do is iterate through possible comma locations in our input string (S) and separate the coordinate pair strings (xStr, yStr).
Then we’ll run into the second challenge, which is to avoid repeating the same processing. If we were to employ a simple nested loop or recursive function to solve this problem, it would end up redoing the same processes many times, since both coordinates can have a decimal.
What we actually want is the product of two loops. The basic solution would be to create two arrays and iterate through their combinations, but there’s really no need to actually build the second array, since we can just as easily process the combinations while we iterate through the second coordinate naturally.
So we should first build and validate all decimal options for the xStr of a given comma position and store the valid possibilities in an array (xPoss). Once this is complete we should find each valid decimal option for yStr, combine it with each value in xPoss, and add the results to our answer array (ans) before moving onto the next comma position.
To aid in this, we can define process, which will either store the valid decimal options from xStr into xPoss or combine valid decimal options from yStr with the contents of xPoss and store the results in ans, depending on which coordinate string we’re currently on (xy).
Once we finish iterating through all comma positions, we can return ans.
Javascript Code:
(Jump to: Problem Description || Solution Idea)
var ambiguousCoordinates = function(S) {
let ans = [], xPoss
const process = (str, xy) => {
if (xy)
for (let x of xPoss)
ans.push(`(${x}, ${str})`)
else xPoss.push(str)
}
const parse = (str, xy) => {
if (str.length === 1 || str[0] !== "0")
process(str, xy)
if (str.length > 1 && str[str.length-1] !== "0")
process(str.slice(0,1) + "." + str.slice(1), xy)
if (str.length > 2 && str[0] !== "0" && str[str.length-1] !== "0")
for (let i = 2; i < str.length; i++)
process(str.slice(0,i) + "." + str.slice(i), xy)
}
for (let i = 2; i < S.length - 1; i++) {
let strs = [S.slice(1,i), S.slice(i, S.length - 1)]
xPoss = []
for (let j = 0; j < 2; j++)
if (xPoss.length || !j) parse(strs[j], j)
}
return ans
};
Enter fullscreen mode Exit fullscreen mode
Python Code:
(Jump to: Problem Description || Solution Idea)
class Solution:
def ambiguousCoordinates(self, S: str) -> List[str]:
ans, xPoss = [], []
def process(st: str, xy: int):
if xy:
for x in xPoss:
ans.append("(" + x + ", " + st + ")")
else: xPoss.append(st)
def parse(st: str, xy: int):
if len(st) == 1 or st[0] != "0":
process(st, xy)
if len(st) > 1 and st[-1] != "0":
process(st[:1] + "." + st[1:], xy)
if len(st) > 2 and st[0] != "0" and st[-1] != "0":
for i in range(2, len(st)):
process(st[:i] + "." + st[i:], xy)
for i in range(2, len(S)-1):
strs, xPoss = [S[1:i], S[i:-1]], []
for j in range(2):
if xPoss or not j: parse(strs[j], j)
return ans
Enter fullscreen mode Exit fullscreen mode
Java Code:
(Jump to: Problem Description || Solution Idea)
class Solution {
private List<String> xPoss, ans;
public List<String> ambiguousCoordinates(String S) {
ans = new ArrayList<>();
for (int i = 2; i < S.length() - 1; i++) {
String[] strs = {S.substring(1,i), S.substring(i, S.length() - 1)};
xPoss = new ArrayList<>();
for (int j = 0; j < 2; j++)
if (xPoss.size() > 0 || j == 0) parse(strs[j], j);
}
return ans;
}
private void parse(String str, int xy) {
if (str.length() == 1 || str.charAt(0) != '0')
process(str, xy);
if (str.length() > 1 && str.charAt(str.length()-1) != '0')
process(str.substring(0,1) + "." + str.substring(1), xy);
if (str.length() > 2 && str.charAt(0) != '0' && str.charAt(str.length()-1) != '0')
for (int i = 2; i < str.length(); i++)
process(str.substring(0,i) + "." + str.substring(i), xy);
}
private void process(String str, int xy) {
if (xy > 0)
for (String x : xPoss)
ans.add("(" + x + ", " + str + ")");
else xPoss.add(str);
}
}
Enter fullscreen mode Exit fullscreen mode
C++ Code:
(Jump to: Problem Description || Solution Idea)
class Solution {
public:
vector<string> ambiguousCoordinates(string S) {
for (int i = 2; i < S.size() - 1; i++) {
string strs[2] = {S.substr(1,i-1), S.substr(i,S.size()-i-1)};
xPoss.clear();
for (int j = 0; j < 2; j++)
if (xPoss.size() > 0 || j == 0) parse(strs[j], j);
}
return ans;
}
private:
vector<string> ans, xPoss;
void parse(string str, int xy) {
if (str.size() == 1 || str.front() != '0')
process(str, xy);
if (str.size() > 1 && str.back() != '0')
process(str.substr(0,1) + "." + str.substr(1), xy);
if (str.size() > 2 && str.front() != '0' && str.back() != '0')
for (int i = 2; i < str.size(); i++)
process(str.substr(0,i) + "." + str.substr(i), xy);
}
void process(string str, int xy) {
if (xy)
for (auto x : xPoss)
ans.push_back("(" + x + ", " + str + ")");
else xPoss.push_back(str);
}
};
Enter fullscreen mode Exit fullscreen mode
Leetcode Solutions (161 Part Series)
1 Solution: Next Permutation
2 Solution: Trim a Binary Search Tree
… 157 more parts…
3 Leetcode Solutions Index
4 Solution: Minimize Deviation in Array
5 Solution: Vertical Order Traversal of a Binary Tree
6 Solution: Count Ways to Make Array With Product
7 Solution: Smallest String With A Given Numeric Value
8 Solution: Linked List Cycle
9 Solution: Path With Minimum Effort
10 Solution: Concatenation of Consecutive Binary Numbers
11 Solution: Minimum Operations to Make a Subsequence
12 Solution: Longest Harmonious Subsequence
13 Solution: Simplify Path
14 Solution: Building Boxes
15 Solution: Decode XORed Permutation
16 Solution: Binary Tree Right Side View
17 Solution: Find Kth Largest XOR Coordinate Value
18 Solution: Change Minimum Characters to Satisfy One of Three Conditions
19 Solution: Shortest Distance to a Character
20 Solution: Peeking Iterator
21 Solution: Convert BST to Greater Tree
22 Solution: Copy List with Random Pointer
23 Solution: Valid Anagram
24 Solution: Number of Steps to Reduce a Number to Zero
25 Solution: Shortest Path in Binary Matrix
26 Solution: Is Graph Bipartite?
27 Solution: Maximum Score From Removing Substrings (ver. 1)
28 Solution: Maximum Score From Removing Substrings (ver. 2)
29 Solution: Sort the Matrix Diagonally
30 Solution: The K Weakest Rows in a Matrix (ver. 1)
31 Solution: The K Weakest Rows in a Matrix (ver. 2)
32 Solution: Letter Case Permutation
33 Solution: Container With Most Water
34 Solution: Arithmetic Slices
35 Solution: Minimum Remove to Make Valid Parentheses
36 Solution: Roman to Integer
37 Solution: Broken Calculator
38 Solution: Find the Most Competitive Subsequence
39 Solution: Longest Word in Dictionary through Deleting
40 Solution: Search a 2D Matrix II
41 Solution: Score of Parentheses
42 Solution: Shortest Unsorted Continuous Subarray
43 Solution: Validate Stack Sequences
44 Solution: Divide Two Integers (ver. 1)
45 Solution: Divide Two Integers (ver. 2)
46 Solution: Maximum Frequency Stack
47 Solution: Distribute Candies
48 Solution: Set Mismatch (ver. 1)
49 Solution: Set Mismatch (ver. 2)
50 Solution: Missing Number
51 Solution: Intersection of Two Linked Lists
52 Solution: Average of Levels in Binary Tree
53 Solution: Short Encoding of Words (ver. 1)
54 Solution: Design HashMap (ver. 1)
55 Solution: Short Encoding of Words (ver. 2)
56 Solution: Design HashMap (ver. 2)
57 Solution: Remove Palindromic Subsequences
58 Solution: Add One Row to Tree
59 Solution: Integer to Roman
60 Solution: Coin Change
61 Solution: Check If a String Contains All Binary Codes of Size K
62 Solution: Binary Trees With Factors
63 Solution: Swapping Nodes in a Linked List
64 Solution: Encode and Decode TinyURL
65 Solution: Best Time to Buy and Sell Stock with Transaction Fee
66 Solution: Generate Random Point in a Circle
67 Solution: Wiggle Subsequence
68 Solution: Keys and Rooms
69 Solution: Design Underground System
70 Solution: Reordered Power of 2
71 Solution: Vowel Spellchecker
72 Solution: 3Sum With Multiplicity
73 Solution: Advantage Shuffle
74 Solution: Pacific Atlantic Water Flow
75 Solution: Word Subsets
76 Solution: Palindromic Substrings
77 Solution: Reconstruct Original Digits from English
78 Solution: Flip Binary Tree To Match Preorder Traversal
79 Solution: Russian Doll Envelopes
80 Solution: Stamping The Sequence
81 Solution: Palindrome Linked List
82 Solution: Ones and Zeroes
83 Solution: Longest Valid Parentheses
84 Solution: Design Circular Queue
85 Solution: Global and Local Inversions
86 Solution: Minimum Operations to Make Array Equal
87 Solution: Determine if String Halves Are Alike
88 Solution: Letter Combinations of a Phone Number
89 Solution: Verifying an Alien Dictionary
90 Solution: Longest Increasing Path in a Matrix
91 Solution: Deepest Leaves Sum
92 Solution: Beautiful Arrangement II
93 Solution: Flatten Nested List Iterator
94 Solution: Partition List
95 Solution: Fibonacci Number
96 Solution: Remove All Adjacent Duplicates in String II
97 Solution: Number of Submatrices That Sum to Target
98 Solution: Remove Nth Node From End of List
99 Solution: Combination Sum IV
100 Solution: N-ary Tree Preorder Traversal
101 Solution: Triangle
102 Solution: Brick Wall
103 Solution: Count Binary Substrings
104 Solution: Critical Connections in a Network
105 Solution: Rotate Image
106 Solution: Furthest Building You Can Reach
107 Solution: Power of Three
108 Solution: Unique Paths II
109 Solution: Find First and Last Position of Element in Sorted Array
110 Solution: Powerful Integers
111 Solution: Prefix and Suffix Search
112 Solution: Course Schedule III
113 Solution: Running Sum of 1d Array
114 Solution: Non-decreasing Array
115 Solution: Jump Game II
116 Solution: Convert Sorted List to Binary Search Tree
117 Solution: Delete Operation for Two Strings
118 Solution: Super Palindromes
119 Solution: Construct Target Array With Multiple Sums
120 Solution: Count Primes
121 Solution: Maximum Points You Can Obtain from Cards
122 Solution: Range Sum Query 2D – Immutable
123 Solution: Ambiguous Coordinates
124 Solution: Flatten Binary Tree to Linked List
125 Solution: Valid Number
126 Solution: Binary Tree Cameras
127 Solution: Longest String Chain
128 Solution: Find Duplicate File in System
129 Solution: Minimum Moves to Equal Array Elements II
130 Solution: Binary Tree Level Order Traversal
131 Solution: Find and Replace Pattern
132 Solution: N-Queens
133 Solution: To Lower Case
134 Solution: Evaluate Reverse Polish Notation
135 Solution: Partitioning Into Minimum Number Of Deci-Binary Numbers
136 Solution: Maximum Product of Word Lengths
137 Solution: Maximum Erasure Value
138 Solution: N-Queens II
139 Solution: Maximum Gap
140 Solution: Search Suggestions System
141 Solution: Max Area of Island
142 Solution: Interleaving String
143 Solution: Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
144 Solution: Open the Lock
145 Solution: Maximum Performance of a Team
146 Solution: Longest Consecutive Sequence
147 Solution: Min Cost Climbing Stairs
148 Solution: Construct Binary Tree from Preorder and Inorder Traversal
149 Solution: Jump Game VI
150 Solution: My Calendar I
151 Solution: Stone Game VII
152 Solution: Minimum Number of Refueling Stops
153 Solution: Palindrome Pairs
154 Solution: Maximum Units on a Truck
155 Solution: Matchsticks to Square
156 Solution: Generate Parentheses
157 Solution: Number of Subarrays with Bounded Maximum
158 Solution: Swim in Rising Water
159 Solution: Pascal’s Triangle
160 Solution: Out of Boundary Paths
161 Solution: Redundant Connection
暂无评论内容