Daily algorithm exercises

2019.2.20

You’re given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.

The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so “a” is considered a different type of stone from “A”.

Example 1:

Input: J = “aA”, S = “aAAbbbb”
Output: 3
Example 2:

Input: J = “z”, S = “ZZ”
Output: 0
Note:

S and J will consist of letters and have length at most 50.
The characters in J are distinct.

My code

class Solution {
   public int numJewelsInStones(String J, String S) {
       HashSet<Character> hs = new HashSet<>();
       for(char c:J.toCharArray()){
           hs.add(c);
       }
       
       int result=0;
       for(char c:S.toCharArray()){
           if(hs.contains(c))
               result++;
         }
        return result;
   }
}
2019.2.21

leetcode
929. Unique Email Addresses
Every email consists of a local name and a domain name, separated by the @ sign.

For example, in alice@leetcode.com, alice is the local name, and leetcode.com is the domain name.

Besides lowercase letters, these emails may contain '.'s or '+'s.

If you add periods (’.’) between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. For example, "alice.z@leetcode.com" and "alicez@leetcode.com" forward to the same email address. (Note that this rule does not apply for domain names.)

If you add a plus (’+’) in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered, for example m.y+name@email.com will be forwarded to my@email.com. (Again, this rule does not apply for domain names.)

It is possible to use both of these rules at the same time.

Given a list of emails, we send one email to each address in the list. How many different addresses actually receive mails?

Example 1:

Input: [“test.email+alex@leetcode.com”,“test.e.mail+bob.cathy@leetcode.com”,“testemail+david@lee.tcode.com”]
Output: 2
Explanation: "testemail@leetcode.com" and "testemail@lee.tcode.com" actually receive mails

Note:

1 <= emails[i].length <= 100
1 <= emails.length <= 100
Each emails[i] contains exactly one ‘@’ character.

My code:

class Solution {
public static int numUniqueEmails(String[] emails) {
    Set<String> normalized = new HashSet<>();
    String part1;
    String part3;
    for(int i =0;i<emails.length;i++){
      if (emails[i].contains("+")){
        part1 = emails[i].substring(0,emails[i].indexOf("+"));
      }else{
        part1= emails[i].substring(0,emails[i].indexOf("@"));
      }
        part3=part1.replaceAll("\\.","");
      String part2=emails[i].substring(emails[i].indexOf("@"));
      String result = part3+part2;
      normalized.add(result);
    }

    return normalized.size();
  }
}
Excellent answer
class Solution {
    public int numUniqueEmails(String[] emails) {
        Set<String> seen = new HashSet();
        for (String email: emails) {
            int i = email.indexOf('@');
            String local = email.substring(0, i);
            String rest = email.substring(i);
            if (local.contains("+")) {
                local = local.substring(0, local.indexOf('+'));
            }
            local = local.replaceAll("\\.", "");
            seen.add(local + rest);
        }

        return seen.size();
    }
}

本题需要注意的地方,String类的replaceall方法的第一个参数并不是简单的字符串,而是一个正则表达式。在正则表达式中,英文点号(.)表示任意字符,所以你原先的写法会把所有字符都替换成空白。
所以,你需要用转义符来在正则表达式中表达普通的点号,写成.,但是字符串中\本身就是转义符,所以还需要再写一个斜杠加在\之前,因此就写成了replaceAll("\.","")

2019.2.22
  1. Replace Words

In English, we have a concept called root, which can be followed by some other words to form another longer word - let’s call this word successor. For example, the root an, followed by other, which can form another word another.

Now, given a dictionary consisting of many roots and a sentence. You need to replace all the successor in the sentence with the root forming it. If a successor has many roots can form it, replace it with the root with the shortest length.

You need to output the sentence after the replacement.

Example 1:

Input: dict = [“cat”, “bat”, “rat”]
sentence = “the cattle was rattled by the battery”
Output: “the cat was rat by the bat”

code:

class Solution {
    public String replaceWords(List<String> dict, String sentence) {
        HashSet<String> wordSet = new HashSet<>();
        for(String word: dict){
          wordSet.add(word);
        }
        StringBuilder ans = new StringBuilder();
        for(String word:sentence.split("\\s+")){
            String prefix="";
            for(int i=1;i<=word.length(); ++i){
                prefix = word.substring(0,i);
                if(wordSet.contains(prefix)){
                    break;
                }
            }
            if(ans.length()>0){
                ans.append(" ");
            }
            ans.append(prefix);
        }
        return ans.toString();
    }
}

2019.2.23
690. Employee Importance

You are given a data structure of employee information, which includes the employee’s unique id, his importance value and his direct subordinates’ id.

For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. They have importance value 15, 10 and 5, respectively. Then employee 1 has a data structure like [1, 15, [2]], and employee 2 has [2, 10, [3]], and employee 3 has [3, 5, []]. Note that although employee 3 is also a subordinate of employee 1, the relationship is not direct.

Now given the employee information of a company, and an employee id, you need to return the total importance value of this employee and all his subordinates.

Example 1:

Input: [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1
Output: 11
Explanation:
Employee 1 has importance value 5, and he has two direct subordinates: employee 2 and employee 3. They both have importance value 3. So the total importance value of employee 1 is 5 + 3 + 3 = 11.

code:

/*
// Employee info
class Employee {
    // It's the unique id of each node;
    // unique id of this employee
    public int id;
    // the importance value of this employee
    public int importance;
    // the id of direct subordinates
    public List<Integer> subordinates;
};
*/
class Solution {
    Map<Integer,Employee> ans = new HashMap<>();
    public int getImportance(List<Employee> employees, int id) {
        for(Employee employee:employees){
            ans.put(employee.id,employee);
        }
        return add(id);
    }
    
    public int add(int id){
        Employee a = ans.get(id);
        int result = a.importance;;
        for(Integer emId: a.subordinates){
            result += add(emId);
        }
        return result;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Fighting_Boss_Hao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值