题一:反转字符串
方法一:借用栈完成
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;
}
}