Common functions implementation

substring

#![allow(unused)]
fn main() {
pub fn sub_string(s: String, start: usize, end: usize) -> String {
s.get(start..=end).unwrap().to_string()
}
}

convert hexadecimal to decimal

/*
十六进制转换为十进制
*/
fn hexadecimal_to_decimal(h: &str) -> i32 {
let mut result = 0;
for c in h.get(2..).unwrap().to_string().chars() {
match c.to_digit(16) {
Some(d) => result = result * 16 + d as i32,
None => return -1,
}
}
result
}
fn main(){
let re = hexadecimal_to_decimal("0xA0");
println!("{}", re);//160
}

parse string to i32

fn parse_to_int(b: &str) -> Option<i32> {
if b.len() == 0 {
return None;
}
let mut res = 0;
for c in b.chars() {
res *= 10;
res += c as i32 - 48;
}
return Some(res);
}
fn main(){
let re = parse_to_int("1014565115");
println!("{:?}", re);
}

binary to decimal

/*
二进制转换为十进制
*/
fn binary_to_decimal(num: &str) -> Option<i64> {
if num.len() == 0 {
return None;
}
let mut sum = 0;
let vec = num
.chars()
.map(|x| i64::from(x.to_digit(10).unwrap()))
.collect::<Vec<i64>>();
for (index, item) in vec.iter().rev().enumerate() {
sum += i64::pow(2, index as u32) * item;
}
Some(sum)
}
fn main(){
let re = binary_to_decimal("101");
println!("{:?}", re);
}

all prime factors

/*
数的所有质数因子
*/
fn all_prime_factors(n: usize) -> Vec<usize> {
let mut n = n as usize;
let mut factors: Vec<usize> = vec![];
for i in 2..n * n {
while n % i == 0 {
factors.push(i);
n /= i;
}
}
factors
}
fn main(){
let re = all_prime_factors(40);
println!("{:?}", re); //[2,2,2,5]
}

round

/*
四舍五入
*/
fn round(f: f64) -> i64 {
(f + 0.5).floor() as i64
}
fn main() {
let re = round(10.4);
assert_eq!(10, re);
}

input from terminal

pub fn input_string() -> String {
let mut input = String::new();
std::io::stdin().read_line(&mut input).unwrap();
input.trim().to_string()
}
pub fn input_num<T>() -> T
where
<T as std::str::FromStr>::Err: std::fmt::Debug,
T: std::str::FromStr,
{
let mut input = String::new();
std::io::stdin().read_line(&mut input).unwrap();
input.trim().to_string().parse::<T>().unwrap()
}
pub fn input_vec_string(split_by: &str) -> Vec<String> {
let mut input = String::new();
std::io::stdin().read_line(&mut input).unwrap();
input
.trim()
.split(split_by)
.filter(|s| !s.is_empty())
.map(|s| s.trim().to_string())
.map(|s| s.to_string())
.collect::<Vec<String>>()
}
pub fn input_vec_num<T>(split_by: &str) -> Vec<T>
where
<T as std::str::FromStr>::Err: std::fmt::Debug,
T: std::str::FromStr,
{
let mut input = String::new();
std::io::stdin().read_line(&mut input).unwrap();
input
.trim()
.split(split_by)
.filter(|s| !s.is_empty())
.map(|s| s.trim().to_string())
.map(|s| s.parse::<T>().unwrap())
.collect::<Vec<T>>()
}
fn input_loop() -> std::io::Lines<std::io::StdinLock<'static>> {
use std::io::{self, *};
let stdin = io::stdin();
stdin.lock().lines()
}
fn main() {
for line in input_loop() {
println!("{}", line.unwrap());
}
}

padding和对齐

#![allow(unused)]
fn main() {
// 右对齐,不足左边补空格
println!("|{:6}|", 21);//|    21|
println!("|{:>6}|", 21);//|    21|
// 右对齐,不足左边补0
println!("{:06}", 21);//000021
println!("{:>06}", 21);//000021
println!("{:0>6}", 21);//000021
// 右对齐,左边补-
println!("{:->6}", 21);//----21
// 居中对齐
println!("|{:^6}|", 21);//|  21  |
// 左对齐,右边补-
println!("|{:-<6}|", 21);//|21----|
}

数组去重

#![allow(unused)]
fn main() {
pub fn huawei_2016_17() {
let s = vec![1, 0, 1, 0, 0, 0, 1];
fn remove_repeat(v: Vec<i32>) -> Vec<i32> {
let mut res = vec![];
for i in 0..v.len() {
if res.contains(&v[i]) {
continue;
} else {
res.push(v[i]);
}
}
res
}
let res = remove_repeat(s);
println!("{:?}", res);//[1,0]
}
}

vertor 中的邻居

#![allow(unused)]
fn main() {
pub fn huawei_2016_18() {
let v = Vec::from("zankxnsk1515-5151xsx45");
let digits = v
.iter()
.enumerate()
.filter(|(i, c)| (**c as char).is_digit(10))
.map(|(i, c)| (i, *c, *c as char))
.collect::<Vec<_>>();
println!("{:?}", digits);
let mut d_iter = digits.iter();
let mut v = vec![];
while let Some(d) = d_iter.next() {
if let Some(d1) = d_iter.next() {
v.push([d.2, d1.2]);
}
}
// [['1', '5'], ['1', '5'], ['5', '1'], ['5', '1'], ['4', '5']]
println!("{:?}", v);
}
}

排序的Vec去重 并return重复的元素数量

fn remove_duplicates_from_sorted_vec(nums: Vec<i32>) -> usize {
if nums.len() < 1 {
return 0;
};
let n = nums.len();
let mut nums = nums.clone();
let mut j = 0;
for i in 0..n {
if nums[j] != nums[i] {
j += 1;
nums[j] = nums[i];
}
}
let (unique, duplicate) = nums.split_at(j + 1);
println!("{:?}", unique); // unique vec
println!("{:?}", duplicate); // duplicate vec
// [0, 1, 2, 3, 4]
// [2, 2, 3, 3, 4]
// 5
return j + 1; //重复的元素数
}
fn main() {
let res = remove_duplicates_from_sorted_vec(vec![0, 0, 1, 1, 1, 2, 2, 3, 3, 4]);
println!("{}", res);
}

判断链表是否有环

public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while (slow != fast) {
if (fast == null || fast.next == null) {
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}

字符串中找出数字 find all digit in string

pub fn findall_digit(s: &str) -> Vec<i64> {
let mut s = s.chars().collect::<Vec<_>>();
let ss = s.clone();
for (i, c) in ss.iter().enumerate() {
if !c.is_digit(10) && i < ss.len() {
s[i] = ' ';
}
}
let s_digit = s.iter().map(|s| s.to_string()).collect::<Vec<_>>().join("");
s_digit
.split(" ")
.filter(|s| !s.is_empty())
.map(|s| s.trim().to_string())
.map(|s| s.parse::<i64>().unwrap())
.collect::<Vec<i64>>()
}
fn main(){
let res = findall_digit("xsxsx54xsxs45x4sx");
println!("{:?}", res); //[54, 45, 4]
}

String 全排列 (full arrangement)

#![allow(unused)]
fn main() {
fn full_arrangement(s: String) -> Vec<String> {
let s_string = s.to_string();
let mut out_vec = Vec::new();
for i in 0..s.len() + 1 {
for j in i + 1..s.len() + 1 {
out_vec.push(s_string.get(i..j).unwrap().to_string());
}
}
out_vec
}
println!("{:?}", full_arrangement("123".to_string())); //["1", "12", "123", "2", "23", "3"]
}

Vec 全排列 (full arrangement)

#![allow(unused)]
fn main() {
fn full_arrangement(s: Vec<i32>) -> Vec<Vec<i32>> {
let mut out_vec = Vec::new();
for i in 0..s.len() + 1 {
for j in i + 1..s.len() + 1 {
out_vec.push(s.get(i..j).unwrap().to_owned());
}
}
out_vec
}
println!("{:?}", full_arrangement(vec![1, 2, 3])); //[[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]
}

Vec 排序

#![allow(unused)]
fn main() {
pub fn permute(nums: Vec<i32>) -> Vec<Vec<i32>> {
if nums.len() <= 1 { return vec![nums]; };
let mut ret = vec![];
for i in 0..nums.len() {
let mut iter_ret = vec![];
let mut cloned_nums = nums.clone();
let index_item = cloned_nums.remove(i);
iter_ret.push(index_item);
for x in Solution::permute(cloned_nums) {
let mut cloned_iter_ret = iter_ret.clone();
cloned_iter_ret.extend(x);
ret.push(cloned_iter_ret);
}
}
ret
}
let ret = vec![
vec![1, 2, 3],
vec![1, 3, 2],
vec![2, 1, 3],
vec![2, 3, 1],
vec![3, 1, 2],
vec![3, 2, 1]
];
assert_eq!(ret, permute(vec![1, 2, 3]));//全排序
}

Vec 组合 (combinations)

pub fn combinations() {
// 组合 Combination
pub struct Combinations<T>
where
T: Ord + Clone,
{
original: Vec<T>,
possition: Vec<usize>,
len: usize,
started: bool,
}
impl<T> Combinations<T>
where
T: Ord + Clone,
{
//new
pub fn new(mut original: Vec<T>, len: usize) -> Self {
if original.len() > len && len >= 1 {
original.sort_unstable();
Self {
original,
possition: (0..len).collect(),
len,
started: false,
}
} else {
panic!("the length has to be smaller then the datasets len");
}
}
//insert
fn insert(&self, col: &mut Vec<T>) {
col.clear();
self.possition
.iter()
.enumerate()
.for_each(|(p, n)| col.insert(p, self.original[*n].clone()))
}
//next
pub fn next_combination(&mut self, mut comb: &mut Vec<T>) -> bool {
if !self.started {
// first pass throught
self.started = true;
self.insert(&mut comb);
true
} else {
let org_len = self.original.len();
// check if we cant bump the back number
if self.original[self.possition[self.len - 1]] == self.original[org_len - 1] {
// locate the number closest behind that needs to be bumped
for i in 2..=self.len {
if self.original[self.possition[self.len - i]]
< self.original[org_len - i]
{
//find the value of the
let lastpos = self.possition[self.len - i];
let val = &self.original[lastpos];
for j in lastpos + 1..org_len {
if *val < self.original[j] {
for k in 0..i {
self.possition[self.len - i + k] = j + k;
}
self.insert(&mut comb);
return true;
}
}
}
}
false
} else {
let mut i = self.possition[self.len - 1];
let current = &self.original[i];
let mut next = current;
while current == next {
i += 1;
next = &self.original[i];
}
self.possition[self.len - 1] = i;
self.insert(&mut comb);
true
}
}
}
}
impl<T> Iterator for Combinations<T>
where
T: Ord + Clone,
{
type Item = Vec<T>;
fn next(&mut self) -> Option<Self::Item> {
let mut vals = Vec::with_capacity(self.len);
if self.next_combination(&mut vals) {
Some(vals)
} else {
None
}
}
}
let mut comb = Combinations::new(vec![1, 2, 3, 4], 3).collect::<Vec<_>>();
println!("{:?}", comb); //[[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]
}
fn main(){
combinations();
}
#![allow(unused)]
fn main() {
let binary_search = |f: Vec<i32>, target: i32| {
let mut low = 0;
let mut high = f.len() - 1;
while low < high {
let mid = f64::floor((high - low) as f64 / 2.) as usize + low;
if f[mid] < target {
low = mid + 1;
} else {
high = mid;
}
}
return low;
};
assert_eq!(binary_search(vec![2, 5, 8], 8),2);
}

HJ4 字符串分割

•输入一个字符串,请按长度为8拆分每个输入字符串并进行输出; •长度不是8整数倍的字符串请在后面补数字0,空字符串不处理。 输入描述: 连续输入字符串(每个字符串长度小于等于100) 输出描述: 依次输出所有分割后的长度为8的新字符串

示例1
输入:
abc
复制
输出:
abc00000
use std::io::{self, *};
fn main() {
let stdin = io::stdin();
unsafe {
for line in stdin.lock().lines() {
let mut ll = line.unwrap();
if ll.len()==8{
println!("{}",ll);
}
else if ll.len()<8{
let z = 8-ll.len();
for i in 0..z{
ll.push('0');
}
println!("{}",ll);
}
else{
let l_vec = ll.split("").filter(|s|!s.is_empty()).map(|s|s.to_string()).collect::<Vec<_>>();
let ll_vec = l_vec.chunks(8).collect::<Vec<_>>();
for ll in ll_vec{
if ll.len()==8{
println!("{}",ll.join(""));
}
else if ll.len()<8{
let mut lll = ll.to_vec();
let z = 8-ll.len();
for i in 0..z{
lll.push("0".to_string());
}
println!("{}",lll.join(""));
}
}
}
}
}
}

chunks windows

#![allow(unused)]
fn main() {
pub fn chunk_windows() {
let a = vec![1, 2, 3];
let a_chunks = a
.iter()
.as_slice()
.chunks(2)
.map(|s| s.to_vec())
.collect::<Vec<_>>();
let a_windows = a
.iter()
.as_slice()
.windows(2)
.map(|s| s.to_vec())
.collect::<Vec<_>>();
println!("{:?}", a_chunks);
println!("{:?}", a_windows);
// [[1, 2], [3]]
// [[1, 2], [2, 3]]
}
}

字母出现次数统计 (count letters)

#![allow(unused)]
fn main() {
//是否有效的字母异位词
pub fn is_anagram(s: String, t: String) -> bool {
//字母出现次数统计
fn count_letter(s: String) -> std::collections::BTreeMap<char, i32> {
use std::collections::BTreeMap;
let mut map: BTreeMap<char, i32> = BTreeMap::new();
for c in s.chars() {
if !map.contains_key(&c) {
map.insert(c, 0);
} else {
*map.get_mut(&c).unwrap() += 1;
}
}
map
}
count_letter(s) == count_letter(t)
}
}