Dễ 0 người đã giải Tỷ lệ chấp nhận 0%

Hamming Distance

Compare two DNA strings position by position and count the differences.

Bạn sẽ học được gì

  • Compare two strings position by position
  • Count mismatches
  • Validate equal lengths

Đề bài

Xem bản dịch

Compare two DNA strings position by position and count the differences. Only characters at the same position are compared; do not insert, delete, or shift characters. No biology knowledge is needed.

Implement hamming_distance(first, second).

Input

first: The first DNA string.

second: The equal-length second DNA string.

Output

Return the number of positions with different characters.

Ràng buộc

Both strings have the same length, from 0 to 100,000. Characters are uppercase A, C, G, or T.

Ví dụ

Ví dụ 1
Đầu vào:
first = "ACCT"
second = "AGCA"

Kết quả mong đợi:
expected = 2
Đầu vào:
std::string first = "ACCT";
std::string second = "AGCA";

Kết quả mong đợi:
long long expected = 2;
Đầu vào:
string first = "ACCT";
string second = "AGCA";

Kết quả mong đợi:
long expected = 2;

Giải thích

The second position is C versus G and the fourth is T versus A. The first and third match: two differences.

Ví dụ 2
Đầu vào:
first = "GATT"
second = "GATT"

Kết quả mong đợi:
expected = 0
Đầu vào:
std::string first = "GATT";
std::string second = "GATT";

Kết quả mong đợi:
long long expected = 0;
Đầu vào:
string first = "GATT";
string second = "GATT";

Kết quả mong đợi:
long expected = 0;

Giải thích

All four positions match, so no differences are counted.

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

Compare both strings one position at a time and count when the characters differ.

Gợi ý 2

A single pass with paired iteration is enough; no rearranging or substring searches are needed.

Gợi ý 3

Remember that equal-length inputs can still be empty, which should yield zero differences.

Độ phức tạp mong đợi

O(n) time, O(1) extra space

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Lời giải đạt tốt nhất của mỗi người. Lời giải nhanh hơn, tốn ít bộ nhớ hơn và được đánh giá cao hơn sẽ đứng trên.

Chưa có lời giải nào đạt. Giải bài này để giành hạng nhất.

Học hỏi từ người khác

Lời giải cộng đồng

Chưa có lời giải nào được chia sẻ. Hãy giải thử thách này để đăng lời giải đầu tiên.