zoukankan      html  css  js  c++  java
  • 389. Find the Difference

    题目:

    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:

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

    链接:https://leetcode.com/problems/find-the-difference/#/description

    3/20/2017

    最后一行如何返回会更好?

     1 public class Solution {
     2     public char findTheDifference(String s, String t) {
     3         int[] cs = new int[256];
     4         int[] ct = new int[256];
     5 
     6         for (int i = 0; i < s.length(); i++)
     7             cs[s.charAt(i)]++;
     8         for (int i = 0; i < t.length(); i++)
     9             ct[t.charAt(i)]++;
    10         for (int i = 0; i < 256; i++) {
    11             if (ct[(char)i] > cs[(char)i]) return (char)i;
    12         }
    13         return '0';
    14     }
    15 }

    别人的非常好的方法,位运算:

    https://discuss.leetcode.com/topic/55912/java-solution-using-bit-manipulation

    1 public char findTheDifference(String s, String t) {
    2     int n = t.length();
    3     char c = t.charAt(n - 1);
    4     for (int i = 0; i < n - 1; ++i) {
    5         c ^= s.charAt(i);
    6         c ^= t.charAt(i);
    7     }
    8     return c;
    9 }

    类似的用char对int的值

    1 public char findTheDifference(String s, String t) {
    2         int charCode = t.charAt(s.length());
    3         // Iterate through both strings and char codes
    4         for (int i = 0; i < s.length(); ++i) {
    5               charCode -= (int)s.charAt(i);
    6               charCode += (int)t.charAt(i); 
    7         }
    8         return (char)charCode;
    9     }
  • 相关阅读:
    JavaEE 第四周
    JavaEE 第三周
    JavaEE 第二周
    JavaEE 第一周
    js字符串方法
    javaee项目库存管理系统总结
    javaee期末团队项目库存管理系统概要信息
    JAVAEE第十一周
    JSON
    Facelets
  • 原文地址:https://www.cnblogs.com/panini/p/6592583.html
Copyright © 2011-2022 走看看