leetcode【389】找不同

╰半橙微兮° 2021-10-03 01:40 360阅读 0赞

Given two strings s and t which consist of only lowercase letters.

String t is generated by random shuffling string s and then add one more letter at a random position.

Find the letter that was added in t.

Example:

  1. Input:
  2. s = "abcd"
  3. t = "abcde"
  4. Output:
  5. e
  6. Explanation:
  7. 'e' is the letter that was added.

解题思路:最近在联系map和set的用法,所以就使用了map来做,时间复杂度:o(n).

  1. public char findTheDifference(String s, String t) {
  2. Map<Character,Integer> map = new HashMap<>();
  3. for(char c:t.toCharArray()){
  4. map.put(c,map.getOrDefault(c,0)+1);
  5. }
  6. for (char c:s.toCharArray()){
  7. if(map.containsKey(c))
  8. map.put(c,map.get(c)-1);
  9. }
  10. for(char c:t.toCharArray()) {
  11. if (map.get(c).intValue() == 1)
  12. return c;
  13. }
  14. return 0;
  15. }

发表评论

表情:
评论列表 (有 0 条评论,360人围观)

还没有评论,来说两句吧...

相关阅读

    相关 389. 不同

    给定两个字符串 s 和 t,它们只包含小写字母。 字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。 请找出在 t 中被添加的字母。 示例 1:

    相关 leetcode389. 不同

    给定两个字符串 s 和 t,它们只包含小写字母。 字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。 请找出在 t 中被添加的字母。 示例: 输入:

    相关 LeetCode389. 不同

    给定两个字符串 s 和 t,它们只包含小写字母。 字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。 请找出在 t 中被添加的字母。 示例: 输入