字符串水题——从LeetCode题海中总结常见套路

字符串的题大部分都很水,但是一些企业机试经常出现(比如华为)

另外不水的题常常和DP/贪心/回溯连在一起比较难,还是多练吧

后面用Golang提交试试水,最近在学Golang,非常有意思

目录

LeetCode面试题58-II.左旋转字符串

LeetCode1108.IP地址无效化

LeetCode面试题01.06.字符串压缩

LeetCode657.机器人能否返回原点

LeetCode.804.唯一摩尔斯密码词

LeetCode709.转换成小写字母

LeetCode1221.分割平衡字符串


LeetCode面试题58-II.左旋转字符串

水题,溜了

字符串水题——从LeetCode题海中总结常见套路_第1张图片

class Solution {
public:
    string reverseLeftWords(string s, int n) {
        string s1;
        for(int i=n;i

LeetCode1108.IP地址无效化

咳咳咳,福利题

字符串水题——从LeetCode题海中总结常见套路_第2张图片

class Solution {
public:
    string defangIPaddr(string address) {
        string s;
        for(int i=0;i

LeetCode面试题01.06.字符串压缩

字符串水题——从LeetCode题海中总结常见套路_第3张图片

一种笨拙的写法:

字符串水题——从LeetCode题海中总结常见套路_第4张图片

class Solution {
public:
    string compressString(string S) {
        string s;
        for(int i=0;i

LeetCode657.机器人能否返回原点

第一次用Golang提交,激动哈哈

字符串水题——从LeetCode题海中总结常见套路_第5张图片

字符串水题——从LeetCode题海中总结常见套路_第6张图片

func judgeCircle(moves string) bool {
    var x,y int;//golang会自动初始化为0
    for i:=0;i

LeetCode.804.唯一摩尔斯密码词

字符串水题——从LeetCode题海中总结常见套路_第7张图片

用C++ set处理,挺快的

字符串水题——从LeetCode题海中总结常见套路_第8张图片

class Solution {
public:
    int uniqueMorseRepresentations(vector& words) {
        string a[26]={".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
        set se;
        for(int i=0;i

Golang用map也挺爽,就是还不太熟

func uniqueMorseRepresentations(words []string) int {
    a :=[]string {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."}
    m := map[string]int{}
    for _,v := range words{
        str := ""
        for _,v1 := range v{
            str+=a[v1-'a']
        }
        m[str]=1
    }
    return len(m)
}

LeetCode709.转换成小写字母

一句Goland偷懒哈哈

Go语言的string模块包含了ToLower和ToUpper函数,用于将字符串转换成小写和大写

func toLowerCase(str string) string {
    return strings.ToLower(str)
}

LeetCode1221.分割平衡字符串

贪心即可

字符串水题——从LeetCode题海中总结常见套路_第9张图片

字符串水题——从LeetCode题海中总结常见套路_第10张图片

C++

class Solution {
public:
    int balancedStringSplit(string s) {
        int Rnum=0,Lnum=0;
        int num = 0;
        for(int i=0;i

Golang

func balancedStringSplit(s string) int {
    Rnum := 0
    Lnum := 0
    num := 0
    for _,value := range s{
        if value=='R'{
            Rnum++
        }else{
            Lnum++
        }
        if Rnum!=0&&Lnum!=0&&Lnum==Rnum{
            Rnum=0
            Lnum=0
            num++
        }
    }
    return num
}

 

后记: 最开始写的时候是三月中下旬,然后咕咕咕咕到现在才搞出来,人类的本质是什么?哈哈哈哈

你可能感兴趣的:(LeetCode,算法—STL与数据结构)