20. Valid Parentheses (Easy)
public static boolean isValid(String s) {
Stack<Byte> stack = new Stack<>();
byte[] bytes = s.getBytes();
int length = s.length();
Byte target;
for (int i = 0; i < length; i++) {
if (bytes[i] == '(' || bytes[i] == '[' || bytes[i] == '{') {
stack.push(bytes[i]);
} else {
if (stack.isEmpty()) {
return false;
}
target = stack.pop();
if ((bytes[i] == ')' && target != '(') ||
(bytes[i] == ']' && target != '[') ||
(bytes[i] == '}' && target != '{')) {
return false;
}
}
}
return stack.isEmpty();
}
複製代碼
71. Simplify Path (Medium)
public static String simplifyPath(String path) {
Stack<String> stack = new Stack<>();
String[] paths = path.split("/");
for (String s : paths) {
if (s.length() == 0) {
continue;
}
if (".".equals(s)) {
continue;
}
if ("..".equals(s)) {
if (!stack.isEmpty()) {
stack.pop();
}
continue;
}
stack.push(s);
}
if (stack.isEmpty()) {
return "/";
}
Stack<String> secondStack = new Stack<>();
while (!stack.isEmpty()) {
secondStack.push(stack.pop());
}
StringBuilder sb = new StringBuilder();
while (!secondStack.isEmpty()) {
sb.append("/").append(secondStack.pop());
}
return sb.toString();
}
複製代碼