|
| 1 | +/** |
| 2 | + * 816. Ambiguous Coordinates |
| 3 | + * https://leetcode.com/problems/ambiguous-coordinates/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * We had some 2-dimensional coordinates, like "(1, 3)" or "(2, 0.5)". Then, we removed all commas, |
| 7 | + * decimal points, and spaces and ended up with the string s. |
| 8 | + * - For example, "(1, 3)" becomes s = "(13)" and "(2, 0.5)" becomes s = "(205)". |
| 9 | + * |
| 10 | + * Return a list of strings representing all possibilities for what our original coordinates could |
| 11 | + * have been. |
| 12 | + * |
| 13 | + * Our original representation never had extraneous zeroes, so we never started with numbers like |
| 14 | + * "00", "0.0", "0.00", "1.0", "001", "00.01", or any other number that can be represented with |
| 15 | + * fewer digits. Also, a decimal point within a number never occurs without at least one digit |
| 16 | + * occurring before it, so we never started with numbers like ".1". |
| 17 | + * |
| 18 | + * The final answer list can be returned in any order. All coordinates in the final answer have |
| 19 | + * exactly one space between them (occurring after the comma.) |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {string} s |
| 24 | + * @return {string[]} |
| 25 | + */ |
| 26 | +var ambiguousCoordinates = function(s) { |
| 27 | + const digits = s.slice(1, s.length - 1); |
| 28 | + const result = []; |
| 29 | + |
| 30 | + for (let i = 1; i < digits.length; i++) { |
| 31 | + const leftPart = digits.substring(0, i); |
| 32 | + const rightPart = digits.substring(i); |
| 33 | + |
| 34 | + const validLeftCoords = getValidCoordinates(leftPart); |
| 35 | + const validRightCoords = getValidCoordinates(rightPart); |
| 36 | + |
| 37 | + for (const left of validLeftCoords) { |
| 38 | + for (const right of validRightCoords) { |
| 39 | + result.push(`(${left}, ${right})`); |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + return result; |
| 45 | +}; |
| 46 | + |
| 47 | +function getValidCoordinates(s) { |
| 48 | + const coords = []; |
| 49 | + |
| 50 | + if (isValidInteger(s)) { |
| 51 | + coords.push(s); |
| 52 | + } |
| 53 | + |
| 54 | + for (let i = 1; i < s.length; i++) { |
| 55 | + const integerPart = s.substring(0, i); |
| 56 | + const decimalPart = s.substring(i); |
| 57 | + |
| 58 | + if (isValidInteger(integerPart) && isValidDecimal(decimalPart)) { |
| 59 | + coords.push(`${integerPart}.${decimalPart}`); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + return coords; |
| 64 | +} |
| 65 | + |
| 66 | +function isValidInteger(s) { |
| 67 | + return s === '0' || s[0] !== '0'; |
| 68 | +} |
| 69 | + |
| 70 | +function isValidDecimal(s) { |
| 71 | + return s[s.length - 1] !== '0'; |
| 72 | +} |
0 commit comments