70、华为面试题:判断字符串对称及数组升序

(1)判断一字符串是不是对称的,如:abccba。

(2)用递归的方法判断整数组a[N]是不是升序排列。

方法一:

通过获取字符串长度,从头尾分别遍历,检验到汇合之前是否出现不同字符。

这种方式,需要遍历数组两次。

C语言实现:

#include<stdio.h>
bool Judge(int arr[],int n){
    for(int j=0,i=n-1;j<n/2;j++){
        if(arr[j]==arr[i]){
            i--;
        }
        else return false;
    }
    return true;
}
int main(){
    int a[7]={1,2,3,4,3,2,1};
    if(Judge(a,7))printf("ok");
    else printf("error");
}

方法二:归并

使用归并排序类似的拆解方法,将拆解的小块进行判断

Python实现:

lst1=[2,4,5,6,4,7]
lst2=[1,3,5,7,9]
flag=True
def judge(lst,start,end):
    global flag
    if flag==False:
        return 0
    if start==end:
        return lst[start]
    else:
        mid=int((start+end)/2)
        if lst[mid]>lst[mid+1]:
            flag=False
        left=judge(lst,start,mid)
        right=judge(lst,mid+1,end)
        if left<right:
            return right
        else:
            flag=False
            return 0

judge(lst1,0,5)
print(flag)
flag=True
judge(lst2,0,4)
print(flag)
False
True

方法三:类遍历式递归

两两一组,逐步向后递归比较,思想上类似于遍历

Python实现:

lst1=[2,4,5,6,4,7]
lst2=[1,3,5,7,9]
def judge_(lst,s,e):
    if e<len(lst):
        if lst[e]<lst[s]:
            return False
        else:
            print(lst[s],lst[e])
            return judge_(lst,s+1,e+1)
    else :
        return True
print(judge_(lst1,0,1))
print(judge_(lst2,0,1))
2 4
4 5
5 6
False
1 3
3 5
5 7
7 9
True

两种递归方法进行对比

lst1=[2,4,5,6,4,7,10,11,12,14,1,16]
lst2=[1,3,5,7,9,10,11,12,13,14,15,10]
time1=time.time()
print(judge_(lst1,0,1))
print(judge_(lst2,0,1))
time2=time.time()
judge(lst1,0,len(lst1)-1)
print(flag)
flag=True
judge(lst2,0,len(lst2)-1)
print(flag)
time3=time.time()
print('time cost : %.5f sec' %(time2-time1))
print('time cost : %.5f sec' %(time3-time2))
2 4
4 5
5 6
False
1 3
3 5
5 7
7 9
9 10
10 11
11 12
12 13
13 14
14 15
False
False
False
time cost : 0.14054 sec
time cost : 0.01562 sec

可以明显看出,方法三的递归时间是方法二的递归时间地十倍左右

所以可以得出结论,归并递归在效率上大于类似于遍历的递归,后者最好使用循环遍历进行实现。


旭旭
1 声望0 粉丝

喜欢算法,欢迎大家给出意见~