Rust leetcode elementary algorithm string code summary

strrev

The easiest solution!

 s.reverse();

Of course, you can write it yourself!

 let len = s.len();
 let mut t: char;
 for i in 0..len / 2 {
 t = s[i];
 s[i] = s[len - i - 1];
 s[len - i - 1] = t;
 }

Integer inversion, if leet writes STD before I32 e.g. std::i32::MAX, official recommendation direct I32

 if x > i32::MAX - 1 || x < i32::MIN || x == i32::MIN {
        return 0;
    }
    let mut x: i64 = x as i64;
    let mut newnum: i64 = 0;
    while x != 0 {
        newnum = newnum * 10 + x % 10 as i64;
        x /= 10;
        if newnum > i32::MAX as i64 || newnum < i32::MIN as i64 {
            return 0;
        }
    }
    return newnum as i32;

The first unique character in a string

First create an array that holds all the letters, then record several times, like checking for duplicates, and then iterate over the original string.

If the character appears only once, it is returned. In order to record the number of times in the first iteration, the second iteration is to find only one occurrence while ensuring sequence.

    if s == "" {
        return 0;
    }
    let mut index = 0;
    let mut array = vec![0; 26];
    for c in s.bytes() {
        if array[(c - 97) as usize] != 0 {
            array[(c - 97) as usize] = array[(c - 97) as usize] + 1;
            continue;
        }
        array[(c - 97) as usize] = 1;
    }
    for c in s.bytes() {
        if array[(c - 97) as usize] == 1 {
            return index;
        }
        index = index + 1;
    }
    return -1;

Effective Alphabetic Words

Similar to the previous question, you can first load an array of letters, appearing + 1 in the first string, -1 in the next string, and finally decide if it is equal to 0.

iter.zip(iter) is to compress two iterators together and iterate together, just like cutting two cucumbers, which means cutting side by side.

    if s == t {
        return true;
    }
    if s.len() != t.len() {
        return false;
    }
    let s = s.bytes();
    let t = t.bytes();
    let mut v = vec![0; 26];
    // for _ in 0..s.len() {
    //     let st = s.next().unwrap() as usize;
    //     let vt = t.next().unwrap() as usize;
    //     v[st - 97] = v[st - 97] + 1;
    //     v[vt - 97] = v[vt - 97] - 1;
    // }
    for (a, b) in s.zip(t) {
        v[a as usize - 97] = v[a as usize - 97] + 1;
        v[b as usize - 97] = v[b as usize - 97] - 1;
    }
    for e in v.iter() {
        if *e != 0 {
            return false;
        }
    }
    return true;

Verify Palindrome String

What is a palindrome string? Simply put, reading while reading is the same as reading over, that is, comparing whether the subscripts [i] and [len-i-l] are equal or not;

Feel the elegance of Rust!

    let chars = s
        .chars()
        .filter(|x| x.is_ascii_alphanumeric())
        .map(|x| x.to_ascii_lowercase())
        .collect::<Vec<char>>();
    for (a, b) in chars[0..(chars.len() / 2)].iter().zip(chars.iter().rev()) {
        if a != b {
            return false;
        }
    }
    true

String Conversion Integer (atoi)

My idea is to use match to match characters and add valid characters to the string, taking into account "+ - 0", which are the four characters and other characters. Whenever + - appears, followed by no numbers, the loop ends with spaces, but once 0 + - appears, the parsable string is marked.

Then there's the following garbage code. Suggest that you run a little and see what others are writing. Sometimes the code below is 0ms and sometimes 4ms.

    let mut result = String::new();
   // This flag is a plus or minus sign, which is multiplied by the final result let mut bz_fuhao
= 0;
   // This is the start token, meaning that a parsable string may appear after 0 + - let mut bz_kaishi
= 0; for c in s.chars() { match c {
       // Clear spaces first
' ' => {
         // But the start marker changes and the loop ends when a space occurs
if bz_kaishi != 0 { break; } continue; }
       // 0 is not added to the result until a valid number, but 0 appears to mark the beginning of character collection
'0' => { if result == "" { bz_kaishi = 1; continue; } if result != "" { result.push(c); } }
       // This is the normal character collection
'1'..='9' => { bz_kaishi = 1; result.push(c); }
       // Symbol bits appear
'-' => {
         // If you start collecting characters but appear again - you'll end up
if bz_kaishi != 0 { break; }          // Collected characters are not empty - they end too if result != "" { break; }
         // Indicates that once a - sign has been collected, an end loop occurs again
if bz_fuhao != 0 { break; }
         // The -sign appears when the collected character is empty, and then is collected
if result == "" { bz_fuhao = -1; bz_kaishi = 1; continue; } }
        // Similar to minus sign
'+' => { if bz_kaishi != 0 { break; } if result != "" { break; } if bz_fuhao != 0 { break; } if result == "" { bz_fuhao = 1; bz_kaishi = 1; continue; } }
        // Other characters end directly _
=> break, } } // 2147483647 -2147483648
  // If it does not appear + replace the symbol bit with 1;
if bz_fuhao == 0 { bz_fuhao = 1; }
  // Judge Length
if result.len() > 10 && bz_fuhao == 1 { return 2147483647; } if result.len() > 10 && bz_fuhao == -1 { return -2147483648; }
  // Just parse without overflowing match result.parse::
<i128>() { Ok(o) => { if o * bz_fuhao < -2147483648 { return -2147483648; } if o * bz_fuhao > 2147483647 { return 2147483647; } return (o * bz_fuhao) as i32; } Err(_) => return 0, }

Implement strStr()

This is a short string that can slide several times over a long string. To put it simply, you have a box of 7 and a box of 6.

Slide from start to finish, once, and twice if it's 5 lengths, think about how many position states start one plus the number of slides.

len_h - len_n + 1 is the character that a long string can cut out. Cut out the length of the short string each time to compare.

        if needle == ""||haystack == needle{
            return 0;
        }
        let len_h = haystack.len();
        let len_n = needle.len();
        let mut haystack = haystack;
        if len_h < len_n {
            return -1
        }
        for i in 0..len_h-len_n+1{
            if haystack.split_at(len_n).0 == needle{
                return i as i32
            }
            haystack = haystack.split_at(1).1.into();
        }
        return -1;

Look-and-say sequence

Parsing starts with knowing what the appearance column is and then looks at the code for yourself. I'm also confused.

        if  n == 1 {
            return "1".into();
        }
        let mut res = String::new();
        let str_t = Solution::count_and_say(n-1);
        let len = str_t.len();
        let mut t = 0;
        for i in 1..len+1 {
            if  i == len{
                res.push_str(&(i - t).to_string());
                res.push_str(str_t.get(t..t+1).unwrap());
                return res;
            }else if str_t.get(i..i+1) != str_t.get(t..t+1){
                res.push_str(&(i - t).to_string());
                res.push_str(str_t.get(t..t+1).unwrap());
                t = i;
            } 
        }
        res

Longest Common Prefix

First declare an end flag bit, the idea is to find a string at random, preferably the first string, and iterate over it, comparing one character at a time to determine if it is the same location as the other strings.

Ends when they are not the same, and intercepts the characters before the end glyph. Note that the return outside the for loop needs to be added 1, otherwise the intercept is incomplete.

        let len  = strs.len();
        if len == 0 {
            return "".into();
        }
        if len  == 1 {
            return strs[0].clone();
        }
        let len0 = strs[0].len();
        if len0 == 0 {
            return "".into();
        }
        let mut t = 0;
        for i in 0..len0{
                t =i;
                let strs0t = strs[0].get(i..i+1).unwrap_or_default();
                if strs0t == ""{
                    return strs[0].get(0..t).unwrap().into(); 
                }
                for j in 1..len {
                    if 0 == strs[j].len(){
                        return "".into(); 
                    }
                    let strsit = strs[j].get(i..i+1).unwrap_or_default();
                    if strs0t == ""{
                        return strs[0].get(0..t).unwrap().into(); 
                    }
                    if strs0t == strsit {
                        continue
                    }else{
                        return strs[0].get(0..t).unwrap().into(); 
                    }
                }      
        }
        return  strs[0].get(0..t+1).unwrap().into(); 

This is the end. The previous algorithm wasted space on a blog. It feels good to be together and easy to see.

Tags: Algorithm

Posted by FoTo50 on Wed, 25 May 2022 04:51:23 +0300