Reverse String by Words
String description = "Java technology blog for smart java concepts and coding practices";
// reverse string builder
StringBuilder reverseString = new StringBuilder();
// Put words from String in Stack
Stack<String> myStack = new Stack<>();
StringTokenizer tokenizer = new StringTokenizer(description, " ");
while (tokenizer.hasMoreTokens()) {
myStack.push(tokenizer.nextToken());
}
//Pop each word from stack and append in builder
while (!myStack.empty()) {
reverseString.append(myStack.pop() + " ");
}
System.out.println(reverseString.toString());
public String simplifyPath(String path) {
String[] parts = path.split("/");
Stack<String> stack = new Stack<String>();
// put parts into stack
for(int i = 0; i < parts.length; i++) {
// ignore . and double slash
if(parts[i].equals("") || parts[i].equals(".")) {
continue;
} else if(parts[i].equals("..")) {
// go back in case of ..
if(!stack.empty()) stack.pop();
} else {
// put all else into stack
stack.push(parts[i]);
}
}
if(stack.empty()) return "/";
String result = "";
while(!stack.empty()) {
result = "/"+stack.pop()+result;
}
return result;
}
Valid Parenteses with Stack
public boolean isValidParentheses(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch == '(' || ch == '[' || ch == '{') {
stack.push(ch);
} else {
if (stack.empty() || Math.abs(stack.pop() - ch) > 2) return false;
}
}
return stack.empty(); // statck.empty represents brackets closed in the correct order
}