Skip to content

Commit 947c2fc

Browse files
author
Prashant Jain
committed
Added more String problems
1 parent 0f8f72d commit 947c2fc

2 files changed

Lines changed: 99 additions & 0 deletions

File tree

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package in.knowledgegate.dsa.strings;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
/**
7+
* Given n pairs of parentheses, write a function
8+
* to generate all combinations of well-formed
9+
* parentheses.
10+
*
11+
* Example 1:
12+
* Input: n = 3
13+
* Output: ["((()))","(()())","(())()","()(())","()()()"]
14+
*
15+
* Example 2:
16+
* Input: n = 1
17+
* Output: ["()"]
18+
*
19+
* Constraints:
20+
* 1 <= n <= 8
21+
*/
22+
public class GenerateParentheses {
23+
24+
public static void main(String[] args) {
25+
GenerateParentheses obj =
26+
new GenerateParentheses();
27+
System.out.println("Here is the result:");
28+
for (String combi :
29+
obj.generateParenthesis(3)) {
30+
System.out.print(combi + ", ");
31+
}
32+
}
33+
34+
public List<String> generateParenthesis(int n) {
35+
List<String> combinations = new ArrayList<>();
36+
generateAllCombinations(new char[n*2], 0,
37+
combinations);
38+
return combinations;
39+
}
40+
41+
private void generateAllCombinations(char[] current,
42+
int pos, List<String> combinations) {
43+
if (pos == current.length) {
44+
if (isValid(current)) {
45+
combinations.add(new String(current));
46+
}
47+
} else {
48+
current[pos] = '(';
49+
generateAllCombinations(current, pos + 1,
50+
combinations);
51+
current[pos] = ')';
52+
generateAllCombinations(current, pos + 1,
53+
combinations);
54+
}
55+
}
56+
57+
private boolean isValid(char[] current) {
58+
int counter = 0;
59+
for (int i = 0; i < current.length; i++) {
60+
if (current[i] == '(') {
61+
counter++;
62+
} else {
63+
counter--;
64+
}
65+
if (counter < 0) return false;
66+
}
67+
return counter == 0;
68+
}
69+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package in.knowledgegate.dsa.strings;
2+
3+
/**
4+
* Write a function that reverses a string. The
5+
* input string is given as an array of characters
6+
* s.
7+
* You must do this by modifying the input array
8+
* in-place with O(1) extra memory.
9+
*
10+
* Example 1:
11+
* Input: s = ["h","e","l","l","o"]
12+
* Output: ["o","l","l","e","h"]
13+
*
14+
* Example 2:
15+
* Input: s = ["H","a","n","n","a","h"]
16+
* Output: ["h","a","n","n","a","H"]
17+
*
18+
* Constraints:
19+
* 1 <= s.length <= 105
20+
* s[i] is a printable ascii character.
21+
*/
22+
public class ReverseString {
23+
public void reverseString(char[] s) {
24+
for (int i = 0; i < s.length / 2; i++) {
25+
char temp = s[i];
26+
s[i] = s[s.length - 1 - i];
27+
s[s.length - 1 - i] = temp;
28+
}
29+
}
30+
}

0 commit comments

Comments
 (0)