Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit6e19c74

Browse files
committed
Create 1963-minimum-number-of-swaps.cpp
1 parentec27ad3 commit6e19c74

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/*
2+
Approach:
3+
Just check which '[' brackes are wrongly placed correct that bracket.
4+
use stack to keep track of bracket
5+
6+
Time complexity : O(n)
7+
Space complexity: O(n)
8+
9+
n is length of the string.
10+
*/
11+
12+
classSolution {
13+
public:
14+
intminSwaps(string s) {
15+
16+
int answer=0;
17+
18+
stack<char> stc;
19+
stc.push(']');
20+
21+
int n = s.size();
22+
23+
for(int i=0;i<n;i++){
24+
char top = stc.top();
25+
26+
if(s[i]==']'){
27+
28+
// is the '[' bracket correctly placed
29+
// if yes then just pop
30+
if (top=='[') {
31+
stc.pop();
32+
}
33+
// if '[' is not correctly placed
34+
// then correct it (push '[')
35+
else{
36+
stc.push('[');
37+
answer++;
38+
}
39+
}
40+
else{
41+
stc.push('[');
42+
}
43+
}
44+
return answer;
45+
}
46+
};

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp