LeetCode 程序面試 Golden Code
LeetCode 程序面試 Golden Code 1-3 題
(關於筆記和刷題,以後多記錄)
面試題 01.01. 判斷一個角色是否獨一無二
我的第一反應是兩個 for 循環可以解決它。
//解法一
class Solution {
public boolean isUnique(String astr) {
for(int i = 0; i<astr.length(); i++)
{
for(int j=i+1; j<astr.length(); j++)
{
if(astr.charAt(i)==astr.charAt(j))
return false;
}
}
return true;
}
}
面試題 01.02. 判斷字符是否排序
要將一個字符串的字符重新排列成另一個字符串,必須滿足兩個條件:
1. 兩個字符串長度相同。
2. 兩個字符串中的每個字符出現的頻率相等
class Solution {
public boolean CheckPermutation(String s1, String s2) {
if(s1.length() != s2.length())
return false;
int []a=new int[256];
for(int k=0; k<s1.length(); k++)
{
a[s1.charAt(k)]++;
a[s2.charAt(k)]--;
}
for(int i:a)
{
if(i!=0)
return false;
}
return true;
}
}
一個[s1.charAt(k)]++;
一個[s2.charAt(k)]- -;
charAt() 的用法:
這裡將int數組中的字符轉換為ascll碼,即數字,如果第一個字符串中有字符,則該位置的int數組加1,最終可以判斷兩個字符串是否相等。
面試題01.03. 轉換為URL
class Solution {
public String replaceSpaces(String S, int length) {
return S.substring(0, length).replace(" ","%20");
}
}
版權聲明:本文為CSDN博主“weixin_46458146”原創文章,受CC 4.0 BY-SA版權協議約束。轉載時請附上原文出處鏈接和本聲明。
原文鏈接:https://blog.csdn.net/weixin_46458146/article/details/114454853
原文鏈接:https://blog.csdn.net/weixin_46458146/article/details/114454853