美文网首页
leetcode的每天一题更新(Find the Differe

leetcode的每天一题更新(Find the Differe

作者: 今天是晴天 | 来源:发表于2017-04-21 09:15 被阅读0次

题目:给两个字符串,一个字符串只比另外一个长一个字符,找出那个字符并且返回。
解题思路:毫无疑问的用异或,自从知道以后感觉只要是求一个不同的数或者是字符用异或是最快而且简洁的办法,其中出了点差错,因为char变量赋值的时候不可以只给一个空的,即‘’,所以只要给它一个‘ ’空格符给它,然后在最后返回的时候再异或一次空格符即可,看了一下别人的解决办法和我的没有什么差别就附上我的代码吧,附上代码:

public class Solution {
    public char findTheDifference(String s, String t) {
         char result=' ';
            for(int i=0;i<s.length()||i<t.length();i++){
                if(i<s.length()&&i<t.length()){
                result ^=(s.charAt(i)^t.charAt(i));
                }
            }
            if(t.length()>s.length()){
                result ^=t.charAt(t.length()-1);
            }else{
                result ^=s.charAt(s.length()-1);
            }
            return (char) (result^' ');
        
    }
}

相关文章

网友评论

      本文标题:leetcode的每天一题更新(Find the Differe

      本文链接:https://www.haomeiwen.com/subject/mvorzttx.html