---
# System prepended metadata

title: '[1554. Strings Differ by One Character](https://leetcode.com/problems/strings-differ-by-one-character/)'
tags: [leetcode]

---

---
tags: leetcode
---

# [1554. Strings Differ by One Character](https://leetcode.com/problems/strings-differ-by-one-character/)
---
# My Solution
## The Key Idea for Solving This Coding Question
## C++ Code
```cpp=
class Solution {
public:
    bool differByOne(vector<string> &dict) {
        unordered_set<string> htbl;

        for (auto &word : dict) {
            if (word.size() > 20) {
                return bruteForce(dict);
            }

            for (int i = 0; i < word.size(); ++i) {
                char orgChar = word[i];

                word[i] = '?';
                if (htbl.count(word) != 0) {
                    return true;
                }
                htbl.insert(word);
                word[i] = orgChar;
            }
        }

        return false;
    }

private:
    bool bruteForce(vector<string> &dict) {
        for (int i = 0; i + 1 < dict.size(); ++i) {
            for (int j = i + 1; j < dict.size(); ++j) {
                if (isDifferByOneChar(dict[i], dict[j])) {
                    return true;
                }
            }
        }
        return false;
    }

    bool isDifferByOneChar(string &word1, string &word2) {
        int i = 0;
        bool firstDiffFound = false;

        while (i < word1.size()) {
            if (word1[i] != word2[i]) {
                if (firstDiffFound) {
                    return false;
                }
                firstDiffFound = true;
            }
            ++i;
        }
        return firstDiffFound;
    }
};
```
## Time Complexity
## Space Complexity
# Miscellane
<!--
# Test Cases
```
["abcd","acbd", "aacd"]
```
```
["ab","cd","yz"]
```
```
["abcd","cccc","abyd","abab"]
```
* Time Limit Exceeded
https://leetcode.com/problems/strings-differ-by-one-character/submissions/848320136/
* Time Limit Exceeded
https://leetcode.com/problems/strings-differ-by-one-character/submissions/856884826/
* Wrong Answer
https://leetcode.com/problems/strings-differ-by-one-character/submissions/869620305/
-->