zoukankan      html  css  js  c++  java
  • 编程之法----面试和算法心得

    第1章 字符串

      1.1 字符串的旋转

        输入一个英文句子,翻转句子中单词的顺序。要求单词内字符的顺序不变,句子中单词以空格符隔开。为简单起见,标点符号和普通字母一样处理。例如:若输入“I am a student.”,则输出“student. a am I”。

    #include <stdio.h>
    
    void ReverseString(char *s, int from, int to);
    
    int main(int argc, const char * argv[]) {
        // insert code here...
        
        char s[] = "I am a student.";
        printf("%s
    ", s);   // I am a student.
        
        int from = 0;
        int to = 0;
        
        for (int i = 0; i < sizeof(s); i ++) {
            if (s[i] == ' ' || s[i] == '') {
                to = i - 1;
                ReverseString(s, from, to);
                from = i + 1;
            }
        }
        printf("%s
    ", s);  // I ma a .tneduts
        
        ReverseString(s, 0, sizeof(s) - 2);
        printf("%s
    ", s);   // student. a am I
        
        return 0;
    }
    
    void ReverseString(char *s, int from, int to) {
        while (from < to) {
            char t = s[from];
            s[from] = s[to];
            s[to] = t;
            from ++;
            to --;
        }
    }

       1.2 字符串的包含

        给定一长字符串a和一短字符串b。请问,如何最快地判断出短字符串b中的所有字符是否都在长字符串a中?

        为简单起见,假设输入的字符串只包含大写英文字母。下面举几个例子。

        (1)如果字符串a是“ABCD”,字符串b是“BAD”,答案是true,因为字符串b中的字母都在字符串a中,或者说b是a的真子集。

        (2)如果字符串a是“ABCD”,字符串b是“BAE”,答案是false,因为字符串b中的字母E不再字符串a中。

        (3)如果字符串a是“ABCD”,字符串b是“AA”,答案是true,因为字符串b中的字母都在字符串a中。

    #include <stdio.h>
    #include <stdbool.h>
    
    bool StringContain(char *a, char *b);
    int length(char *a);
    
    int main(int argc, const char * argv[]) {
        // insert code here...
    
        char a[] = "ABCDEFG";
        char b[] = "BGN";
    
        bool t = StringContain(a, b);
        
        printf("%d
    ", t);
       
        return 0;
    }
    
    int length(char *c) {
        int l = 0;
        while (c[l] != '') {
            l ++;
        }
        return l;
    }
    
    bool StringContain(char *a, char *b) {
        
        int hash = 0;
        int alength = length(a);
        for (int i = 0; i < alength; i ++) {
            
            hash |= 1 << (a[i] - 'A');
        }
        int blength = length(b);
        for (int i = 0; i < blength; i++) {
            
            if ((hash & (1 << (b[i] - 'A'))) == 0) {
                return false;
            }
        }
        return true;
    }
  • 相关阅读:
    案例十:shell编写nginx服务启动程序
    Linux在实际中的应用
    案例九:shell脚本自动创建多个新用户,并设置密码
    数据架构的演变
    第一个Struts2程序
    关于eclipse导入Tomact报404的问题
    单选框 RadioButton
    EditText编辑框
    Button控件的三种点击事件
    1319: 同构词
  • 原文地址:https://www.cnblogs.com/muzijie/p/6628341.html
Copyright © 2011-2022 走看看