Skip to content

Commit 5e87e6d

Browse files
committed
2024-07-22 v. 6.2.5: added "71. Simplify Path"
1 parent 485d437 commit 5e87e6d

File tree

4 files changed

+38
-1
lines changed

4 files changed

+38
-1
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -490,3 +490,4 @@ Profile on LeetCode: [fartem](https://leetcode.com/fartem/).
490490
| 59. Spiral Matrix II | [Link](https://leetcode.com/problems/spiral-matrix-ii/) | [Link](./lib/medium/59_spiral_matrix_ii.rb) |
491491
| 61. Rotate List | [Link](https://leetcode.com/problems/rotate-list/) | [Link](./lib/medium/61_rotate_list.rb) |
492492
| 62. Unique Paths | [Link](https://leetcode.com/problems/unique-paths/) | [Link](./lib/medium/62_unique_paths.rb) |
493+
| 71. Simplify Path | [Link](https://leetcode.com/problems/simplify-path/) | [Link](./lib/medium/71_simplify_path.rb) |

leetcode-ruby.gemspec

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ require 'English'
55
::Gem::Specification.new do |s|
66
s.required_ruby_version = '>= 3.0'
77
s.name = 'leetcode-ruby'
8-
s.version = '6.2.4'
8+
s.version = '6.2.5'
99
s.license = 'MIT'
1010
s.files = ::Dir['lib/**/*.rb'] + %w[README.md]
1111
s.executable = 'leetcode-ruby'

lib/medium/71_simplify_path.rb

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# frozen_string_literal: true
2+
3+
# https://leetcode.com/problems/simplify-path/
4+
# @param {String} path
5+
# @return {String}
6+
def simplify_path(path)
7+
stack = []
8+
s = path.split('/')
9+
10+
s.each do |str|
11+
if str == '..'
12+
stack.pop unless stack.empty?
13+
elsif str != '.' && !str.empty? && str != '..'
14+
stack << "/#{str}"
15+
end
16+
end
17+
18+
return '/' if stack.empty?
19+
20+
stack.join
21+
end

test/medium/test_71_simplify_path.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# frozen_string_literal: true
2+
3+
require_relative '../test_helper'
4+
require_relative '../../lib/medium/71_simplify_path'
5+
require 'minitest/autorun'
6+
7+
class SimplifyPathTest < ::Minitest::Test
8+
def test_default
9+
assert_equal('/home', simplify_path('/home/'))
10+
assert_equal('/home/foo', simplify_path('/home//foo/'))
11+
assert_equal('/home/user/Pictures', simplify_path('/home/user/Documents/../Pictures'))
12+
assert_equal('/', simplify_path('/../'))
13+
assert_equal('/.../b/d', simplify_path('/.../a/../b/c/../d/./'))
14+
end
15+
end

0 commit comments

Comments
 (0)