题解 | #反转字符串# | Rust

反转字符串

https://www.nowcoder.com/practice/c3a6afee325e472386a1c4eb1ef987f3

struct Solution{

}

impl Solution {
    fn new() -> Self {
        Solution{}
    }

    /**
    * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
    *
    * 反转字符串
        * @param str string字符串 
        * @return string字符串
    */
    pub fn solve(&self, str: String) -> String {
        // write code here
        let mut str = str;
        let (mut low, mut high) = (0, str.len() as i32 -1);
        while low < high {
            let c_l = str.as_bytes()[low as usize];
            let c_h = str.as_bytes()[high as usize];
            unsafe {
                str.as_bytes_mut()[low as usize] = c_h;
                str.as_bytes_mut()[high as usize] = c_l;
            }
            low+=1;
            high-=1;
        }
        return str
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务