校招算法笔面试 | 校招笔面试真题-字符串连连看

题目## 题目

题目链接

解题思路

这是一个字符串模拟题,关键点在于:

  1. 需要重复扫描直到无法消除
  2. 使用栈来维护当前保留的字符
  3. 记录连续相同字符的个数

关键点

  1. 使用栈来处理字符串
  2. 需要考虑消除后新产生的连续字符
  3. 重复处理直到字符串不再变化

代码

#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Solution {
public:
    string removeRepeated(string s) {
        bool changed = true;
        
        while (changed) {
            changed = false;
            string result;
            vector<pair<char, int>> stack;  // 字符和其连续出现次数
            
            // 处理每个字符
            for (char c : s) {
                if (stack.empty() || stack.back().first != c) {
                    // 新字符,压入栈
                    stack.push_back({c, 1});
                } else {
                    // 相同字符,增加计数
                    stack.back().second++;
                    
                    // 如果达到3个或以上
                    if (stack.back().second >= 3) {
                        stack.pop_back();
                        changed = true;
                    }
                }
            }
            
            // 重建字符串
            for (const auto& p : stack) {
                result.append(p.second, p.first);
            }
            
            // 更新字符串
            if (changed) {
                s = result;
            }
        }
        
        return s;
    }
};

int main() {
    string s;
    cin >> s;
    
    Solution solution;
    cout << solution.removeRepeated(s) << endl;
    
    return 0;
}

public class Main {
    static class CharCount {
        char ch;
        int count;
        
        CharCount(char ch, int count) {
            this.ch = ch;
            this.count = count;
        }
    }
    
    static class Solution {
        public String removeRepeated(String s) {
            boolean changed = true;
            
            while (changed) {
                changed = false;
                StringBuilder result = new StringBuilder();
                ArrayList<CharCount> stack = new ArrayList<>();
                
                // 处理每个字符
                for (char c : s.toCharArray()) {
                    if (stack.isEmpty() || stack.get(stack.size()-1).ch != c) {
                        // 新字符,压入栈
                        stack.add(new CharCount(c, 1));
                    } else {
                        // 相同字符,增加计数
                        CharCount last = stack.get(stack.size()-1);
                        last.count++;
                        
                        // 如果达到3个或以上
                        if (last.count >= 3) {
                            stack.remove(stack.size()-1);
                            changed = true;
                        }
                    }
                }
                
                // 重建字符串
                for (CharCount cc : stack) {
                    // 使用循环替代repeat方法
                    for (int i = 0; i < cc.count; i++) {
                        result.append(cc.ch);
                    }
                }
                
                // 更新字符串
                if (changed) {
                    s = result.toString();
                }
            }
            
            return s;
        }
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.next();
        
        Solution solution = new Solution();
        System.out.println(solution.removeRepeated(s));
        
        sc.close();
    }
}
class Solution:
    def remove_repeated(self, s: str) -> str:
        changed = True
        
        while changed:
            changed = False
            stack = []  # [(char, count)]
            
            # 处理每个字符
            for c in s:
                if not stack or stack[-1][0] != c:
                    # 新字符,压入栈
                    stack.append([c, 1])
                else:
                    # 相同字符,增加计数
                    stack[-1][1] += 1
                    
                    # 如果达到3个或以上
                    if stack[-1][1] >= 3:
                        stack.pop()
                        changed = True
            
            # 重建字符串
            result = ''.join(c * count for c, count in stack)
            
            # 更新字符串
            if changed:
                s = result
        
        return s

def main():
    s = input().strip()
    solution = Solution()
    print(solution.remove_repeated(s))

if __name__ == "__main__":
    main()

算法及复杂度

  • 算法:栈 + 模拟
  • 时间复杂度: O ( n 2 ) \mathcal{O}(n^2) O(n2),其中 n n n 是字符串长度(最坏情况下需要多次扫描)
  • 空间复杂度: O ( n ) \mathcal{O}(n) O(n),需要栈来存储字符

题目链接

解题思路

  1. 题目要求计算字符串 T T T S S S 中所有长度为 ∣ T ∣ |T| T 的子串的距离和
  2. 字符串距离定义:对应位置字符不同的数量
  3. 解题策略:
    • 使用滑动窗口统计当前窗口中’a’和’b’的数量
    • 对于 S S S 中的每个字符,根据它与 T T T 中对应位置字符的不同来累加距离
    • 当窗口移动时,更新字符计数

代码

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s, t;
    cin >> s >> t;
    
    long long lens = s.length();
    long long lent = t.length();
    long long count_a = 0, count_b = 0, total = 0;
    int pos = 0;
    
    // 遍历字符串S
    for(int i = 0; i < lens; i++) {
        // 统计T中字符数量
        if(i < lent) {
            if(t[i] == 'a') count_a++;
            else count_b++;
        }
        
        // 计算距离
        if(s[i] == 'a') {
            total += count_b;  // 与'b'不同
        } else {
            total += count_a;  // 与'a'不同
        }
        
        // 更新滑动窗口
        if(i >= lens - lent) {
            if(t[pos++] == 'a') count_a--;
            else count_b--;
        }
    }
    
    cout << total << endl;
    return 0;
}
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.next();
        String t = sc.next();
        
        long lens = s.length();
        long lent = t.length();
        long countA = 0, countB = 0, total = 0;
        int pos = 0;
        
        // 遍历字符串S
        for(int i = 0; i < lens; i++) {
            // 统计T中字符数量
            if(i < lent) {
                if(t.charAt(i) == 'a') countA++;
                else countB++;
            }
            
            // 计算距离
            if(s.charAt(i) == 'a') {
                total += countB;  // 与'b'不同
            } else {
                total += countA;  // 与'a'不同
            }
            
            // 更新滑动窗口
            if(i >= lens - lent) {
                if(t.charAt(pos++) == 'a') countA--;
                else countB--;
            }
        }
        
        System.out.println(total);
    }
}
s = input()
t = input()

lens = len(s)
lent = len(t)
count_a = count_b = total = pos = 0

# 遍历字符串S
for i in range(lens):
    # 统计T中字符数量
    if i < lent:
        if t[i] == 'a':
            count_a += 1
        else:
            count_b += 1
    
    # 计算距离
    if s[i] == 'a':
        total += count_b  # 与'b'不同
    else:
        total += count_a  # 与'a'不同
    
    # 更新滑动窗口
    if i >= lens - lent:
        if t[pos] == 'a':
            count_a -= 1
        else:
            count_b -= 1
        pos += 1

print(total)

算法及复杂度

  • 算法:滑动窗口
  • 时间复杂度: O ( ∣ S ∣ ) \mathcal{O}(|S|) O(S) - 只需要遍历一次字符串S
  • 空间复杂度: O ( 1 ) \mathcal{O}(1) O(1) - 只需要常数级别的额外空间
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值