2020年3月8日 星期日

[Codility] 第七課 Brackets



簡而言之,這題目就是要判斷 S 字串是否有對稱的括號,就返回 1。
利用 Stack 後進先出的方式來一一判別對稱則 pop 出來,最後是空的就是對稱了。


題目


A string S consisting of N characters is considered to be properly nested if any of the following conditions is true:
  • S is empty;
  • S has the form "(U)" or "[U]" or "{U}" where U is a properly nested string;
  • S has the form "VW" where V and W are properly nested strings.
For example, the string "{[()()]}" is properly nested but "([)()]" is not.
Write a function:
class Solution { public int solution(String S); }
that, given a string S consisting of N characters, returns 1 if S is properly nested and 0 otherwise.
For example, given S = "{[()()]}", the function should return 1 and given S = "([)()]", the function should return 0, as explained above.
Write an efficient algorithm for the following assumptions:
  • N is an integer within the range [0..200,000];
  • string S consists only of the following characters: "(", "{", "[", "]", "}" and/or ")".


Java 程式碼
  1. // you can also use imports, for example:
  2. import java.util.*;
  3.  
  4. class Solution {
  5. public int solution(String S) {
  6. // write your code in Java SE 8
  7. if(S.length() == 0)
  8. return 1;
  9. if(S.length() > 200000)
  10. return 0;
  11. Stack st = new Stack();
  12. for(int i=0; i< S.length();i++){
  13. char ch = S.charAt(i);
  14. if(ch == '{' || ch == '(' || ch == '['){
  15. st.push(S.charAt(i));
  16. }else{
  17. if(st.empty()){
  18. return 0;
  19. }
  20. char stPeek =(char) st.peek();
  21. if(ch == '}' && stPeek == '{'){
  22. st.pop();
  23. }
  24. if(ch == ']' && stPeek == '['){
  25. st.pop();
  26. }
  27. if(ch == ')' && stPeek == '('){
  28. st.pop();
  29. }
  30. }
  31. }
  32. if(st.empty()){
  33. return 1;
  34. }else{
  35. return 0;
  36. }
  37. }
  38. }

分數共拿 100%
任何問題歡迎交流討論,一起學習!

更多面試相關

⇒ [Codility] 面試寫題目經驗感想



感謝相關連結
https://www.codility.com/
https://app.codility.com/programmers/lessons/7-stacks_and_queues/brackets/

沒有留言:

張貼留言