登录
OAmaster

Given typedText containing uppercase and lowercase English letters, return upper_count - lower_count.

Example: typedText = "AbCd" → upper = 2, lower = 2, answer = 0.

解法

单次遍历,分别统计大写和小写字母数后相减。复杂度 O(n)

def letter_case_diff(s: str) -> int:
 return sum(1 for c in s if c.isupper()) - sum(1 for c in s if c.islower())
class Solution {
    static int letterCaseDiff(String s) {
        int u = 0, l = 0;
        for (char c : s.toCharArray()) {
            if (Character.isUpperCase(c)) u++;
            else if (Character.isLowerCase(c)) l++;
        }
        return u - l;
    }
}
#include <string>
#include <cctype>
using namespace std;

int letterCaseDiff(string s) {
 int u = 0, l = 0;
 for (char c : s) {
 if (isupper((unsigned char)c)) u++;
 else if (islower((unsigned char)c)) l++;
 }
 return u - l;
}

A bird builds a nest by collecting sticks in a forest. forest[] non-negative integers; non-zero = stick of that length, zero = empty cell. Start at index bird, fly right searching the next non-zero cell, take it (mark zero), append the stick to the nest. Then flip direction (right → left → right ...). Continue until total nest length ≥ 100. Return 0-based indices of sticks collected, in order.

Example: forest = [3, 0, 50, 0, 80, 0, 25], bird = 0 → fly right, pick 3 at index 0, total 3; flip left → no stick; flip right → pick 50 at index 2, total 53; flip left → no stick; flip right → pick 80, total 133 ≥ 100, stop.

解法

模拟:维护 posdirection;前进直到非零格收走,翻转方向,循环直到总和 ≥ 100 或越界。复杂度 O(n)

def bird_sticks(forest: list[int], bird: int) -> list[int]:
    f = list(forest)
    n = len(f)
    out, total = [], 0
    pos, d = bird, 1
    while total < 100:
        i = pos
        while 0 <= i < n and f[i] == 0:
            i += d
        if i < 0 or i >= n:
            break
        out.append(i)
        total += f[i]
        f[i] = 0
        pos, d = i + d, -d
    return out
import java.util.*;

class Solution {
    static int[] birdSticks(int[] forest, int bird) {
        int n = forest.length, total = 0, pos = bird, dir = 1;
        List<Integer> out = new ArrayList<>();
        while (total < 100) {
            int i = pos;
            while (i >= 0 && i < n && forest[i] == 0) i += dir;
            if (i < 0 || i >= n) break;
            out.add(i);
            total += forest[i];
            forest[i] = 0;
            pos = i + dir;
            dir = -dir;
        }
        int[] arr = new int[out.size()];
        for (int k = 0; k < arr.length; k++) arr[k] = out.get(k);
        return arr;
    }
}
#include <vector>
using namespace std;

vector<int> birdSticks(vector<int> forest, int bird) {
 int n = forest.size(), total = 0, pos = bird, dir = 1;
 vector<int> out;
 while (total < 100) {
 int i = pos;
 while (i >= 0 && i < n && forest[i] == 0) i += dir;
 if (i < 0 || i >= n) break;
 out.push_back(i);
 total += forest[i];
 forest[i] = 0;
 pos = i + dir;
 dir = -dir;
 }
 return out;
}

Events of two types:

  • MESSAGE id<num> <timestamp> <mention_text>mention_text is space-separated tokens of id<num>, ALL, or HERE.
  • OFFLINE id<num> — that user becomes inactive (still exists, but HERE won't count them).

ALL mentions every existing user; HERE mentions every currently-active user. Each mention token counted once per message regardless of repeats; self-mentions count. Return strings "id<num>=<count>" sorted lexicographically.

解法

维护两个集合 all_usersactive_users 和计数表。每条 MESSAGE:把发送者放入两个集合,构造去重 mention 集合,每个成员计数加 1。OFFLINE:仅从 active_users 移除。复杂度 O(total events + total mentions)

def chat_mentions(events: list[str]) -> list[str]:
    all_, active = set(), set()
    cnt = {}
    for ev in events:
        parts = ev.split()
        if parts[0] == "MESSAGE":
            sender = parts[1]
            all_.add(sender); active.add(sender)
            mentioned = set()
            for tok in parts[3:]:
                if tok == "ALL":    mentioned |= all_
                elif tok == "HERE": mentioned |= active
                else:               mentioned.add(tok)
            for m in mentioned:
                cnt[m] = cnt.get(m, 0) + 1
        else:
            active.discard(parts[1])
    return [f"{k}={v}" for k, v in sorted(cnt.items())]
import java.util.*;

class Solution {
    static List<String> chatMentions(List<String> events) {
        Set<String> all = new HashSet<>(), active = new HashSet<>();
        Map<String, Integer> cnt = new TreeMap<>();
        for (String ev : events) {
            String[] parts = ev.split("\\s+");
            if (parts[0].equals("MESSAGE")) {
                String sender = parts[1];
                all.add(sender); active.add(sender);
                Set<String> mentioned = new HashSet<>();
                for (int i = 3; i < parts.length; i++) {
                    if (parts[i].equals("ALL"))       mentioned.addAll(all);
                    else if (parts[i].equals("HERE")) mentioned.addAll(active);
                    else                              mentioned.add(parts[i]);
                }
                for (String m : mentioned) cnt.merge(m, 1, Integer::sum);
            } else {
                active.remove(parts[1]);
            }
        }
        List<String> out = new ArrayList<>();
        for (var e : cnt.entrySet()) out.add(e.getKey() + "=" + e.getValue());
        return out;
    }
}
#include <vector>
#include <string>
#include <sstream>
#include <unordered_set>
#include <map>
using namespace std;

vector<string> chatMentions(vector<string>& events) {
 unordered_set<string> all_, active;
 map<string, int> cnt;
 for (auto& ev : events) {
 stringstream ss(ev);
 vector<string> parts;
 string tok;
 while (ss >> tok) parts.push_back(tok);
 if (parts[0] == "MESSAGE") {
 const string& sender = parts[1];
 all_.insert(sender); active.insert(sender);
 unordered_set<string> mentioned;
 for (int i = 3; i < (int)parts.size(); i++) {
 if (parts[i] == "ALL") mentioned.insert(all_.begin(), all_.end());
 else if (parts[i] == "HERE") mentioned.insert(active.begin(), active.end());
 else mentioned.insert(parts[i]);
 }
 for (auto& m : mentioned) cnt[m]++;
 } else {
 active.erase(parts[1]);
 }
 }
 vector<string> out;
 for (auto& [k, v] : cnt) out.push_back(k + "=" + to_string(v));
 return out;
}
Pro 会员

解锁剩余 15 道 OA 真题

开通后立即解锁完整题面 + Python / Java / C++ 三语题解。 全站 165 家公司 · 1000+ 道 OA · 月度更新。