Skip to content

Commit dfe489a

Browse files
committed
add unix path and target sum
1 parent f485486 commit dfe489a

File tree

3 files changed

+35
-0
lines changed

3 files changed

+35
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ This is my way of saying - change your interview style. There are lots of smart
1717
| [House Robber](https://leetcode.com/problems/house-robber/description/) | [click](https://github.com/sagivo/algorithms/blob/master/src/house-robber.rb) |
1818
| [Coin change](https://leetcode.com/problems/coin-change/description/) | [click](https://github.com/sagivo/algorithms/blob/master/src/coin-change.rb) |
1919
| [Decode Strings](https://leetcode.com/problems/decode-string/description/) | [click](https://github.com/sagivo/algorithms/blob/master/src/decode_string.rb) |
20+
| [Unix path](https://leetcode.com/problems/simplify-path/description/) | [click](https://github.com/sagivo/algorithms/blob/master/src/simplify_path.rb) |
2021
| [Array Product](https://leetcode.com/problems/product-of-array-except-self/description/) | [click](https://github.com/sagivo/algorithms/blob/master/src/product-of-array.rb) |
2122
| [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/description/) | [click](https://github.com/sagivo/algorithms/blob/master/src/top-k-elements.rb) |
2223
| [Sum 4 arrays](https://leetcode.com/problems/4sum-ii/description/) | [click](https://github.com/sagivo/algorithms/blob/master/src/4-sum.rb) |

src/simlify_path.rb

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# @param {String} path
2+
# @return {String}
3+
def simplify_path(path)
4+
dirs = path.split("/")
5+
stack = []
6+
7+
dirs.each do |dir|
8+
next if dir.empty? || dir == "."
9+
if dir == ".."
10+
stack.pop unless stack.empty?
11+
else
12+
stack.push(dir)
13+
end
14+
end
15+
16+
"/" + stack.join("/")
17+
end
18+
19+
p simplify_path("/a/./b/../../c/") # => "/c"

src/target_sum.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# @param {Integer[]} nums
2+
# @param {Integer} s
3+
# @return {Integer}
4+
def find_target_sum_ways(nums, s, i = 0, dp = {})
5+
return dp["#{s}-#{i}"] if dp["#{s}-#{i}"]
6+
if i == nums.size
7+
return dp["#{s}-#{i}"] = s == 0 ? 1 : 0
8+
end
9+
10+
return dp["#{s}-#{i}"] ||=
11+
find_target_sum_ways(nums, s + nums[i], i+1, dp) +
12+
find_target_sum_ways(nums, s - nums[i], i+1, dp)
13+
end
14+
15+
p find_target_sum_ways([1, 1, 1, 1, 1], 3) # => 5

0 commit comments

Comments
 (0)