iT邦幫忙

2024 iThome 鐵人賽

DAY 9
0
自我挑戰組

Leetcode 解題之旅:逐日攻克系列 第 9

每日一LeetCode(9)

  • 分享至 

  • xImage
  •  

389.Find the Difference

題目敘述:

You are given two strings s and t.
String t is generated by random shuffling string s and then add one more letter at a random position.
Return the letter that was added to t.

  • Example 1:
    Input: s = "abcd", t = "abcde"
    Output: "e"
    Explanation: 'e' is the letter that was added.

  • Example 2:
    Input: s = "", t = "y"
    Output: "y"


方法:

  • 建立一個大小為 26 的陣列 Alphabet 來統計每個字母的出現次數。
  • 迭代字串 t 並增加字母表中每個字元的計數。
  • 迭代字串 s 並減少字母表中每個字元的計數。
  • 迭代字母表並找到計數非零的字符,它代表 t 中的額外字符。
  • 返回上一步中找到的字元。

class Solution {
public:
    char findTheDifference(string s, string t) 
    {
        char alphabets[26]={0};
        char ans;
        for(int i=0;i<t.length();i++)
            alphabets[t[i]-'a']++;
        for(int i=0;i<s.length();i++)
            alphabets[s[i]-'a']--;
        for(int i=0;i<26;i++)
        {
            if(alphabets[i]!=0)
            {
                ans=i+'a';
                break;
            }
        }  
        return ans;  
    }
};

上一篇
每日一LeetCode(8)
下一篇
每日一LeetCode(10)
系列文
Leetcode 解題之旅:逐日攻克17
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言