carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode1790:Check if One String Swap Can Make Strings Equal #281

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Direction

You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.

Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the strings. Otherwise, return false.

Example 1:

Input: s1 = "bank", s2 = "kanb" Output: true Explanation: For example, swap the first character with the last character of s2 to make "bank".

Example 2:

Input: s1 = "attack", s2 = "defend" Output: false Explanation: It is impossible to make them equal with one string swap.

Example 3:

Input: s1 = "kelb", s2 = "kelb" Output: true Explanation: The two strings are already equal, so no string swap operation is required.

Constraints:

1 <= s1.length, s2.length <= 100 s1.length == s2.length s1 and s2 consist of only lowercase English letters.

carloscn commented 1 year ago

analysis

pub fn are_almost_equal(s1: &str, s2: &str) -> bool
{
    if s1.len() < 1 || s1.len() != s2.len() {
        return true;
    }

    let s1_vec:Vec<char> = s1.chars().collect();
    let s2_vec:Vec<char> = s2.chars().collect();
    let mut d1:char = '\0';
    let mut d2:char = '\0';
    let mut first:bool = true;
    for i in 0..s1_vec.len() {
        if s1_vec[i] != s2_vec[i] && first == true {
            d1 = s1_vec[i];
            d2 = s2_vec[i];
            first = false;
        } else if s1_vec[i] != s2_vec[i] && first == false {
            if d1 != s2_vec[i] && d2 != s1_vec[i] {
                return false;
            }
        }
    }

    return true;
}
carloscn commented 1 year ago

code

https://review.gerrithub.io/c/carloscn/structstudy/+/556855 https://github.com/carloscn/structstudy/commit/800336a376cdb3b3d50044971c14cacad10d5e0c