rust - string right shift with space complexity O(1)

describe

Given a string of length n, how to achieve circular right shift k bits, k may be greater than n

plan

Use the undafe keyword to convert the string to a slice and operate on the original slice.

accomplish

lib.rs

use std::string::String;

#[derive(Debug)]
struct ShirftString {
    string :String,
    length : usize,
}

impl ShirftString {
    pub fn new(string:String)->ShirftString{
        string.is_ascii();
        let length = string.len();
        ShirftString{
            string,
            length,
        }
    }
    fn swap(&mut self,a:usize,b:usize){
        assert!(a<self.length && b<self.length);
        unsafe{
            let slice = self.string.as_bytes_mut();
            slice.swap(a,b);
        }
    }

    fn get_swap_index(&self,index:usize,shift_amount:usize) -> usize{
        let mut temp = (index+self.length-shift_amount)%self.length;
        while temp < index{
            temp = (temp+self.length-shift_amount)%self.length
        }
        return temp;
    }
    pub fn right_shirft(&mut self,shift_amount:usize){
        let _shift_amount = shift_amount%self.length;
        let mut swap_index:usize;
        for i in 0..self.length{
            swap_index = self.get_swap_index(i,_shift_amount);
            self.swap(i,swap_index);
        }
    }

    pub fn get_string(&self)->&String{
        &self.string
    }
    
}

main.rs

extern crate shirftstring;

fn main() {
    let mut s = ShirftString::new("hello world".to_string());
    s.right_shirft(5);
    println!("{}",s.get_string());
    
}

 

Detailed Algorithm

~ blablabla ~

summary

> rust neither str nor string:String type can be read or modified by index;

> The above scheme does not support strings encoded other than ASCII

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326928555&siteId=291194637