Leetcode389
生活随笔
收集整理的這篇文章主要介紹了
Leetcode389
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Find the Difference
Given two strings s and t which consist of only lowercase letters.
給出兩個字符串,s和t,都是只有小寫字母組成的。
String t is generated by random shuffling string s and then add one more letter at a random position.
字符串t是由字符串s其中在隨機的位置添加一個字符組成的。
Find the letter that was added in t.
找出在t中增加的字符
Example:
Input: s = "abcd" t = "abcde"Output: eExplanation: 'e' is the letter that was added.我一開始的想法就是把每個字符加起來,然后連個字符串相差的字符對應的數,就是對應的不同的字符了,很難說明白就直接看代碼好了。
char c = 0;
for (int i=0;i<t.length();i++)
{
c += t.charAt(i);
}
for (int i=0;i<s.length();i++)
{
c -= s.charAt(i);
}
return c
之后看了討論區,發現有一個異或好方法,但是無論怎么想都沒想通。只能先記下了。 public char findTheDifference(String s, String t) {char c = 0;for (int i = 0; i < s.length(); ++i) {c ^= s.charAt(i);}for (int i = 0; i < t.length(); ++i) {c ^= t.charAt(i);}return c; }
轉載于:https://www.cnblogs.com/linkstar/p/5891108.html
總結
以上是生活随笔為你收集整理的Leetcode389的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Could not obtain con
- 下一篇: 汤家凤:可以跳过接力题典强化篇直接动手真