字符串操作算法

本文深入探讨了最长递增子序列算法的实现细节,并提供了去除C代码注释的方法,同时还介绍了BF匹配算法、字符串操作函数的实现原理及代码示例。

最长递增子序列

int getMaxSmaller(int array[], int i)
{
	if (i < 1)
		return -1;
	while (array[i-1] > array[i]) {
		--i;
		if (i < 1)
			return -1;
	}
	return i;
}

int getMaxIncreaseSeq(int array[], int length)
{
	//输入出错处理
	if (array == NULL || length <= 0)
		return -1;
	int dairy[2][length] = {0};
	int max = 0, max_start = 0;
	dairy[0][0] = 0;
	dariy[1][0] = 1;
	for (int i = 1; i < length; i++) {
		int pos = i-1;
		if (dairy[1][i-1] > array[i]) {
			pos = getMaxSmaller(array, i);
			if (pos < 0) {
				dairy[0][i] = i;
				dairy[0][i-1] = 0;
				continue;
			} 
		}
		dariy[1][i] = dariy[1][pos] + 1;
		dairy[0][i] = dairy[0][pos]; 
	}
	return dairy[1][length-1];
}

去掉C代码中的注释


没有考虑字符串的//与/**/的问题

#include <string.h>
#include <fstream>
using namespace std;
 
#define PATH_LENGTH 100
#define BUFFER_LENGTH 512 
#define LINE_LENGTH 128
 
int _clearComments(char *buffer, int size, bool& singleFlag, bool& multiFlag)
{
    int current = 0, start = 0, length = 0;
    int ret = size;
 
    while (current < size) {
        switch(buffer[current]) {
        case '/':
            if (!multiFlag && !singleFlag) {
                //not set any flags
                current++;
                if (current >= size) {
                    break;
                }
                length++;
                if (buffer[current] == '*') {
                    multiFlag = true;
                    start = current - 1;
                    length = 2;
                } else if (buffer[current] == '/') {
                    singleFlag = true;
                    start = current - 1;
                    length = 2;
                }
            }
            break;
        case '*':
            if (multiFlag) {
                current++;
                if (current >= size) {
                    break;
                }
                length++;
 
                if (buffer[current] == '/') {
                    memset(buffer+start, ' ', length);
                    length = 0;
                    multiFlag = false;
                }
            }
            break;
        case '\n':
            if (singleFlag) {
                memset(buffer+start, ' ', length);
                length = 0;
                singleFlag = false;
            }
            break;
        default:
            break;
        }
        current++;
        length++;
    }
 
    if (singleFlag || multiFlag) {
        singleFlag = false;
        multiFlag = false;
        memset(buffer+start, ' ', length);
        ret = size - length;
    }
 
    return ret;
}

void clearComments(ifstream& fileIn, ofstream& fileOut)
{
    char buffer[BUFFER_LENGTH];
    bool singleFlag = false, multiFlag = false;
    int buf_size = 0, writeChars = 0;
    int file_length = 0;
    int count = 0;
 
    //get length of the file 
    fileIn.seekg(0, ios::end);
    file_length = fileIn.tellg();
    fileIn.seekg(0, ios::beg);
 
    while (file_length > 0) {
        fileIn.read(buffer, BUFFER_LENGTH);
        buf_size = strlen(buffer);
        writeChars = _clearComments(buffer, buf_size, singleFlag, multiFlag);
        fileOut.write(buffer, writeChars);
        memset(buffer, '\0', BUFFER_LENGTH);
        file_length -= buf_size;
    }
}

int main (int argc, char *argv[]) {
 
    int ret = 0;
    char fileInPath[PATH_LENGTH], fileOutPath[PATH_LENGTH];
    int path_len = 0;
 
    cout << "File path:>";
    cin >> fileInPath;
 
    ifstream fileIn(fileInPath);
    if (!fileIn) {
        cout << "Open file to read failed!" << endl;
        return 0;
    }   
    
    snprintf(fileOutPath, PATH_LENGTH,"%s_%s", fileInPath, "bkp");
    ofstream fileOut(fileOutPath);
    if (!fileOut) {
        cout << "Open file to write failed!" << endl;
        fileIn.close();
        return 0;
    }   
 
    clearComments(fileIn, fileOut); 
    fileOut << flush;
    fileOut.close();
 
    ret = rename(fileOutPath,fileInPath);
 
    return 0;
}


BF算法


算法简介

>一种普通的模式匹配算法,BF算法的思想如下:

①就是将目标串s的第一个字符与模式串P的第一个字符进行匹配;

② 若相等,则继续比较S的第二个字符和P的第二个字符,重复②直到匹配结束

③ 若不相等,则比较S的第二个字符和P的第一个字符,回到①;

算法实现

int BFMacth( char *s, char *p)
{
   if (s == NULL || p == NULL)
        return -1;

    int i = 0, j = 0;
    int lenS = strlen(s), lenP = strlen(p);

    while(i < lenS) {

        j = 0;

        while(s[i] == p[j] && j < lenP) {
            i++, j++;
        }
        if (j == lenP)
            return i - lenP;

        //将i回溯
        i = i - j + 1;
    }
    return -1;

}

整型转化为字符串

char * int2str(int num, int radix){
    int flag = 0, cnt = 0, pos = 0;
    char tmp;

    //整数的最大值为:(2^31-1),有10位
    char *str = (char *)malloc(sizeof(char) * 12);

    //将负数转化为正数
    if (num < 0){
        flag = 1;
        num *=-1;
    }
    while(num) {
        str[cnt++] = '0'+ num % radix;
        num /= radix;
    }
    if (flag) {
        str[cnt] = '-';
    } else {
        str[cnt] = '+';
    }
    str[cnt+1] = '\0';

    pos = 0; 
    while(pos < (cnt - pos)) {
        tmp = str[pos];
        str[pos] = str[cnt-pos];
        str[cnt-pos] = tmp;
        pos++;
    }
    return str;

}

strcmp的实现(比较两个字符串)

int strcmp(const char *str1, const char *s2)
{
    assert(str1 == NULL || str2 == NULL);
    while(*str1 == *str2) {

        if(*str1 == '\0')

            return 0;

        str1++;

        str2++;

    }
    return *str1-*str2;

}

strcpy的实现(字符串的拷贝)

char * strcpy(char *d, const char *s)
{
    char *r = d;

    assert(d == NULL || s == NULL);

    while(*s){
        *d++ = *s++;

    }
    return r;

}

strlen的实现

int strlen(char *s){
    assert(s == NULL);

    int count = 0;

    while(*s) {
        count++;
    }
    return count;

}

strstr(寻找子串出现的位置)

char *strstr(const char *s1, const char *s2)
{
    int len2;

    assert(s1 == NULL || s2 == NULL);

    if (!(len2 = strlen(s2))) {
        return (char *)s1;
    }

    for (; *s1; ++s1) {
        if (*s1 == *s2 && strcmp(s1,s2,len2) == 0) {
            return (char *)s1;
        }
    }
    return NULL;

}

字符串是否只有不重复的字符组成

int test_bit(int *arr, int index)
{
    assert(index < 0 || index > 51);

    int i = 0;

    if (index & (0x01 << 5)) {
        i = 1;
    }else{
        i = 0;
    }
    return arr[i] & (0x01 << (index % 32));
}

void set_bit(int *array, int index)
{
    assert(index < 0 || index > 51);
    int i = 0;
    if (index & (0x01 << 5)) {
        i = 1;
    }else{
        i = 0;
    }
    array[i] = array[i] | (0x01 << index % 32);
}

int isStrDuplicate(char * str, int len)
{
    int flag = 1, index = 0;
    int array[2] = {0};
    char *p = str;
   
    if (str == NULL || len <= 0) {
        return flag;
    }
    for (i = 0; i < len; i++,p++) {

        index = (*p - 'a');
        if (test_bit(array, index)) {
            return flag;
        } else {
            set_bit(array, index);
        }
    }
    flag = 0;

    return flag;
}

将一个句子按单词反序

分析

可以分两步走。step1: 将整个句子反序;step2: 将每一个单词再次反序

代码实现

void reverse(char * array, int start, int end){
    int flag = (end - start) % 2;

    char tmp;

    if (array == NULL || start >= end || start < 0 || end < 0) {
        return;
    }
    while((start+1) < (end-flag)){
        tmp = array[start];
        array[start] = array[end];
        array[end] = tmp;
        start++;
        end--;
    }
}

void reverse_statement(char *str, int len)
{
    int tmp = 0, prev = 0, cnt=len;

    if(str == NULL || len <=0){
        return;
    }

    reverse(str, 0, len-1);

    while(cnt > 0 && prev < len){
        tmp = 0;
        while(str[tmp] != ' ' && str[tmp] != '\0')
            tmp++;
        reverse(array, prev, tmp-1);
        cnt -= tmp;
        prev = tmp+1;
    }
    printf("Statement: [%s]\n", str);

}











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值