Character class is different from String class in some way?..


  • 0
    P
    public class Solution {
        public boolean isValid(String s) {
            LinkedList<String> result=new LinkedList<String>();
            int len=s.length();
            if(len==0)return true;
            for(int i=0;i<len;i++){
                if(s.charAt(i)=='('||s.charAt(i)=='['||s.charAt(i)=='{')
                    result.add(String.valueOf(s.charAt(i)));
                else if(s.charAt(i)==')'||s.charAt(i)==']'||s.charAt(i)=='}'){
                    if(result.isEmpty())return false;
                    else {
                        String x=result.removeLast();
                        if(s.charAt(i)==')'&&!x.equals("("))return false;
                        if(s.charAt(i)==']'&&!x.equals("["))return false;
                        if(s.charAt(i)=='}'&&!x.equals("{"))return false;
                    }
                }
            }
            return result.isEmpty();
            //forget that result should be empty
        }
    }
    
    
    
    public class Solution {
        public boolean isValid(String s) {
            LinkedList<Character> result=new LinkedList<Character>();
            int len=s.length();
            if(len==0)return true;
            for(int i=0;i<len;i++){
                if(s.charAt(i)=='('||s.charAt(i)=='['||s.charAt(i)=='{')
                    result.add(s.charAt(i));
                else if(s.charAt(i)==')'||s.charAt(i)==']'||s.charAt(i)=='}'){
                    if(result.isEmpty())return false;
                    else {
                        Character x=result.removeLast();
                        if(s.charAt(i)==')'&&x!='(')return false;
                        if(s.charAt(i)==']'&&x!='[')return false;
                        if(s.charAt(i)=='}'&&x!='{')return false;
                    }
                }
            }
            return result.isEmpty();
            //forget that result should be empty
        }
    }
    

    Both of the two is right. However, if I change the previous one !x,equals to x!=.., then the previous on is wrong. So is it because String compares the reference of the object, but Character is actually compares the value of the object?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.