初级算法日志-反转字符串、整数反转、字符串中的第一个唯一字符-C#

题一:反转字符串

方法一:借用栈完成

public class Solution {
    public void ReverseString(char[] s) {
        int len = s.Length; //C#中数组有Length()方法,获取数组的长度
        Stack<char> stack = new Stack<char>();
        for(int i=0;i<len;i++){
            stack.Push(s[i]);
        }
        for(int i=0;i<len;i++){
            s[i]=stack.Pop();
        }

    }
}

方法二:借用辅助变量,空间复杂度O(1)

public class Solution {
    public void ReverseString(char[] s) {
        char temp;
        for(int i=0;i<s.Length/2;i++){
            temp=s[i];
            s[i]=s[s.Length-1-i];
            s[s.Length-1-i]=temp; 
        }


    }
}

题二:整数反转

public class Solution {
    public int Reverse(int x) {
        int result=0;

        while(x!=0){
            int num=x%10;
            int newRes=result*10+num;
            if((newRes-num)/10!=result) //判断是否溢出,若溢出直接返回0
                return 0;
            result = newRes;
            x=x/10;
        }
        return result;
    }
}

题三:返回字符串中的第一个唯一字符的索引号

public class Solution {
    public int FirstUniqChar(string s) {
        int length = s.Length; //Length获取字符串长度的方法
        char[] chars = s.ToCharArray(); //将字符串中的子字符串转换为字符数组,
        // 该方法可以添加参数 ToCharArray (int startIndex, int length);
        int[] index = new int[26]; //用来存储字符出现的次数
        for(int i=0; i<length;i++){
            index[chars[i]-'a']++;
        }
        for(int i=0;i<length;i++){
            if(index[chars[i]-'a']==1)
                return i;
        }
        return -1;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值