登录
OAmaster

Imagine you are developing a tool for authors that helps them analyze their writing patterns to enhance consistency. One feature of this tool involves examining the structure of words within a text. You are given a string text that represents a paragraph of words consisting of English letters (both uppercase and lowercase) separated by spaces.

Your task is to find all words in the string that start and end with the same letter, considering that the letter may appear in different cases (e.g., a word may start with an 'a' and end with an 'A'). Return the number of such words as an integer.

  • text = "Level Wow not now" -> 2 (Level, Wow)
  • text = "" -> 0

解法

按空白切分,对每个词比较首尾小写字符。复杂度 O(L)L 为文本总长。

def solution(text):
    cnt = 0
    for w in text.split():
        if w and w[0].lower() == w[-1].lower():
            cnt += 1
    return cnt
class Solution {
    static int solution(String text) {
        int cnt = 0;
        for (String w : text.split("\\s+")) {
            if (w.isEmpty()) continue;
            char a = Character.toLowerCase(w.charAt(0));
            char b = Character.toLowerCase(w.charAt(w.length() - 1));
            if (a == b) cnt++;
        }
        return cnt;
    }
}
#include <string>
#include <sstream>
#include <cctype>
using namespace std;

int solution(string text) {
 stringstream ss(text);
 string w;
 int cnt = 0;
 while (ss >> w) {
 char a = tolower(w.front());
 char b = tolower(w.back());
 if (a == b) cnt++;
 }
 return cnt;
}

You are helping the bird build its nest. You are given an array forest, containing positive integers and zeros, and a non-negative integer bird, representing the bird's initial position. Each positive integer within forest[i] represents the height of the i-th stick. Each zero within forest[i] represents that this place is empty.

Initially, the bird is located at forest[bird], which is guaranteed to be zero. The bird builds the nest, following the algorithm:

  • The bird flies to the right until it finds a stick.
  • The bird flies back to its initial position and attaches the found stick to the nest.
  • The bird repeats steps one and two, but changes the flight direction—it now flies to the left.
  • The bird will repeat steps one and two, changing to the opposite direction each time, until the total length of the sticks in the nest reaches 100.

It is guaranteed that the total length of all sticks in the forest is greater or equal to 100. The bird begins flight to the right.

Follow the process and return the array containing 0-based indices within the initial forest array of every stick found by the bird, in the order in which it was found.

Example

forest = [50, 0, 0, 40, 0, 30, 0, 20], bird = 1
Right -> idx 3 (40), nest 40. Left -> idx 0 (50), nest 90.
Right -> idx 5 (30), nest 120 (>=100, stop).
Answer: [3, 0, 5]

解法

模拟:从 bird 沿当前方向扫,跳过 0 直到遇到木棒或边界;记录下标、累加高度、置零、翻转方向。最坏复杂度 O(n)

def solution(forest, bird):
    n = len(forest)
    forest = forest[:]
    direction = 1
    nest = 0
    out = []
    while nest < 100:
        i = bird + direction
        while 0 <= i < n and forest[i] == 0:
            i += direction
        if not (0 <= i < n):
            break
        out.append(i)
        nest += forest[i]
        forest[i] = 0
        direction *= -1
    return out
import java.util.*;

class Solution {
    static int[] solution(int[] forest, int bird) {
        int[] f = forest.clone();
        int n = f.length, dir = 1, nest = 0;
        List<Integer> out = new ArrayList<>();
        while (nest < 100) {
            int i = bird + dir;
            while (i >= 0 && i < n && f[i] == 0) i += dir;
            if (i < 0 || i >= n) break;
            out.add(i);
            nest += f[i];
            f[i] = 0;
            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> solution(vector<int> forest, int bird) {
 int n = forest.size(), dir = 1, nest = 0;
 vector<int> out;
 while (nest < 100) {
 int i = bird + dir;
 while (i >= 0 && i < n && forest[i] == 0) i += dir;
 if (i < 0 || i >= n) break;
 out.push_back(i);
 nest += forest[i];
 forest[i] = 0;
 dir = -dir;
 }
 return out;
}

You are a molecular biologist working in a research laboratory that studies protein folding patterns. You have a square matrix representing a microscopic view of a protein structure, where each cell contains one of three possible molecular states: 0 (inactive), 1 (partially active), or 2 (fully active).

Your research has identified a specific molecular pattern that indicates optimal protein stability: a "Y-shaped" molecular pathway. This pattern consists of two diagonal molecular chains extending from the upper corners down to the center, plus a vertical chain extending downward from the center.

Your task is to determine the minimum number of molecular state changes required to transform the current protein matrix into one that exhibits this stable Y-pattern.

The Y-pattern is achieved when:

  • All molecular states along the diagonals from the upper-left and upper-right corners down to the center are identical.
  • All molecular states along the vertical path from the center downward are identical to the diagonal states.
  • All other molecular states (the background) are identical to each other but different from the Y-pattern states.

For a square matrix of size n x n, there are exactly 6 possible Y-pattern configurations. The Y-pattern states and background states can be any combination of the three molecular states (0, 1, 2) as long as they are different from each other.

Example

matrix = [[0,1,0],
 [1,1,1],
 [0,1,0]]
n = 3, center = 1. Y cells: (0,0),(0,2),(1,1),(2,1). Background: rest.
Trying ys=1, bg=0: cost = mismatches in Y (1) + mismatches in bg (1) = 2.
Better combos may exist. Answer: 1

解法

预处理 4n-2 个 Y 形格子;枚举 6 种 (Y 颜色, 背景颜色) 组合,分别统计 Y 区与背景区不匹配数。复杂度 O(n² · 9)

def solution(matrix):
    n = len(matrix)
    center = n // 2
    Y = set()
    for i in range(n):
        for j in range(n):
            if (i <= center and (j == i or j == n - 1 - i)) or (i > center and j == center):
                Y.add((i, j))
    bg = {(i, j) for i in range(n) for j in range(n)} - Y
    best = float('inf')
    for ys in range(3):
        for bs in range(3):
            if ys == bs:
                continue
            cost = sum(1 for (i, j) in Y if matrix[i][j] != ys) \
                 + sum(1 for (i, j) in bg if matrix[i][j] != bs)
            best = min(best, cost)
    return best
class Solution {
    static int solution(int[][] m) {
        int n = m.length, center = n / 2;
        boolean[][] isY = new boolean[n][n];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                if ((i <= center && (j == i || j == n - 1 - i)) || (i > center && j == center))
                    isY[i][j] = true;
        int best = Integer.MAX_VALUE;
        for (int y = 0; y < 3; y++) {
            for (int bg = 0; bg < 3; bg++) {
                if (y == bg) continue;
                int cost = 0;
                for (int i = 0; i < n; i++)
                    for (int j = 0; j < n; j++)
                        if (isY[i][j] ? m[i][j] != y : m[i][j] != bg) cost++;
                best = Math.min(best, cost);
            }
        }
        return best;
    }
}
#include <vector>
#include <climits>
using namespace std;

int solution(vector<vector<int>>& m) {
 int n = m.size(), center = n / 2;
 vector<vector<bool>> isY(n, vector<bool>(n, false));
 for (int i = 0; i < n; i++)
 for (int j = 0; j < n; j++)
 if ((i <= center && (j == i || j == n - 1 - i)) || (i > center && j == center))
 isY[i][j] = true;
 int best = INT_MAX;
 for (int y = 0; y < 3; y++) {
 for (int bg = 0; bg < 3; bg++) {
 if (y == bg) continue;
 int cost = 0;
 for (int i = 0; i < n; i++)
 for (int j = 0; j < n; j++)
 if (isY[i][j] ? m[i][j] != y : m[i][j] != bg) cost++;
 best = min(best, cost);
 }
 }
 return best;
}
Pro 会员

解锁剩余 1 道 OA 真题

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